Last active
June 15, 2018 17:59
-
-
Save eday69/6331d9f7d0cd81e6f9c97a529cbfd306 to your computer and use it in GitHub Desktop.
Intermediate Algorithm Scripting: Sum All Numbers in a Range
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// We'll pass you an array of two numbers. Return the sum of those two numbers plus the sum of all the numbers between them. | |
// The lowest number will not always come first. | |
// This was my solution: | |
function sumAll(arr) { | |
let start=arr[0] > arr[1]?arr[1]:arr[0]; | |
let end=arr[0] > arr[1]?arr[0]:arr[1]; | |
let sum=0; | |
for (let i=start; i<=end; i++) { | |
sum+=i; | |
} | |
return sum; | |
} | |
// But this is an awesome solution ! | |
function sumAll(arr) { | |
var sum = 0; | |
for (var i = Math.min(...arr); i <= Math.max(...arr); i++){ | |
sum += i; | |
} | |
return sum; | |
} | |
// Also, I believe this would be a faster solution, specially if the range between numbers is large: | |
function sumAll(arr) { | |
return (Math.abs(arr[0]-arr[1])+1)*(arr[0]+arr[1])/2; | |
} | |
sumAll([1, 4]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment