Skip to content

Instantly share code, notes, and snippets.

@eday69
Last active June 15, 2018 17:59
Show Gist options
  • Save eday69/6331d9f7d0cd81e6f9c97a529cbfd306 to your computer and use it in GitHub Desktop.
Save eday69/6331d9f7d0cd81e6f9c97a529cbfd306 to your computer and use it in GitHub Desktop.
Intermediate Algorithm Scripting: Sum All Numbers in a Range
// 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