DEV Community

Randy Rivera
Randy Rivera

Posted on

Sum Of All Numbers In A Range Problem

  • It's the nighttime and I should be asleep but I decided to post a few problems and tutorials before heading out. Anyways let's Begin.
  • Now I have passed you an array of two numbers. What I want you to do is return the sum of those two numbers plus the sum of all the numbers between them.
  • Example Below. sum([5,1]) should return 15 because sum of all the numbers between 1 and 5 (including both) is 15.
 function sum(arr) {
  return 1;
}

sum([1, 5]);
Enter fullscreen mode Exit fullscreen mode

Answer:

function sum(arr) {
let min = Math.min(arr[0], arr[1])
let max = Math.max(arr[0], arr[1])
let result = 0;

for (let i = min; i <= max; i++) {
    result += i
  }
  return result;
}
console.log(sum([1, 5])); // will display 15;
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)