Review my Solution to Sum All Numbers in a Range

I would appreciate if someone could give me feedback on my solution to the exercise Sum All Numbers in a Range

function sumAll(arr) {
  let max = Math.max(arr[0], arr[1]);
  let min = Math.min(arr[0], arr[1]);
  let arrNumbers = []
  for(let i = min;i <= max;i++){
    arrNumbers.push(i);
  }

  let result = 0;
  for(let i = 0;i < arrNumbers.length;i++){
    result += arrNumbers[i];
  }
  return result;
}

I have added spoiler tags to your code.

As to your code, why are you making the arrNumbers. If you are just making an array to use once, why not just use the values for the array directly.

the array arrNumbers is unnecessary. Otherwise good work.

A little off topic maybe, but isn’t there a slick mathematical formula for finding the sum of a contiguous range of integers? I seem to recall reading a story about how some famous mathematician, as a school kid, was able to answer this question very quickly (I think the range was 1 to 100) when given the problem in class, while the rest of his classmates took a long time since they were basically looping through an array.

1 Like

what you are thinking of is Gauss and him summing 1-100 by realizing the series is equal to:
(1+100)+(2+99)…+(50+51)
which can be rewritten as (101)*50=5050.
Or: n(n+1)/2

Now certain geometric/arithmetic series are worked out and have formulas for them. Notably the sequences involved in the Pascal’s Triangle.

Note in my horribly colorcoded pascal triangle that the sequence we just talked about is right there as the one highlighted in Orange. This is also known as linear numbers.

Pascals triangle has tons of other sequences hidden within such as triangular numbers, tetrahedral numbers, and fibonacci sequence.

2 Likes