Using Aritmetical Progression to solve Sum All Numbers in a Range problem

The related discussion is closed but I don’t understand this solution provided by a user, but I find it pretty elegant as he uses the Aritmetical Progression.

As I read the definition of it, an Aritmetical Progression formula allow to find the nth term of a progression by providing the starting value, the costant that is the difference between the prev and next number, and the position of the unknown number you want to find.

So, aside from the fact that the problem in the title suggest the range provided be an Aritmetical Progression, how can I use that formula to find the sum of all the numbers in between?

The solution provided by the user is confusing to me:

function sumAll (arr) {
    const min = Math.min(...arr);
    const max = Math.max(...arr);
    return (((max - min + 1) * (min + max)) / (2));
}

How did he come up to that?
Why is he dividing by 2?

Please help

1 Like

Well, it’s a pretty well-known formula for this problem.

The Gauss Sum

1 Like