A solution to Sum All Numbers in a Range not already listed

I found a shorter solution than any listed. I don’t know how to submit and it may not be necessary but here it is:

function sumAll(arr) {
  var range = Math.abs(arr[0] - arr[1]) + 1;
  return range *= (arr[0] + arr[1]) / 2;  
}
sumAll([1, 4]);

If you are giving a solution to a problem, please wrap it in [spoiler] tags.

Yes, that is an algebraic reworking of the intermediate solution offered, which is really an adaption of the famous Gauss solution. Personally I don’t like those solutions because they rely on knowledge of a mathematical trick instead of solving it algorithmically, which is the purpose of the unit. But it does work. In a real world application this would be the superior solution as it is faster and cleaner, but that wasn’t really the point of the lesson, imho.

1 Like

Yeah i felt like using math was kind of sleazy. Thank you for the response and sorry about the lack of spoiler tag. I’ll remember next time.

I don’t know if it’s “sleazy”, just not really the point, like the famous story about Gauss. As to the spoiler tags, we all have to be told at one point.