Sum of range of two numbers math equation question

I’ve started working through the intermediate javascript algorithms section in the freecodecamp curriculum and just finished the algorithm that asked to find the sum of a range of numbers given two numbers in an array.

I was able to solve the problem by using Math.min and Math.max and a for loop. My question involves a more straightforward way of solving the problem with a math equation that I found on stackoverflow.

The equation is:

(max - min + 1) * (min + max) / 2

I can do the math and I understand that it works, but I don’t understand how you would even start to create that equation from scratch. Can someone start to explain how people come up with equations like these? I’m not awful with Math, but I’ve never done anything like this before.

that’s a maths algorithm. A programmer wouldn’t come up with it, would google it, find the algorithm in a maths blog or on wikipedia and implement it on JavaScript.

If you are not interested in theoretical maths you don’t want to know how it was found, or even the proof.

1 Like

Probably not the first, but certainly the most famous person to come up with a solution to this problem, much to the annoyance of his teacher, was Carl Friedrich Gauss: https://www.nctm.org/Publications/Teaching-Children-Mathematics/Blog/The-Story-of-Gauss/

That link gives a good explanation about the thought process behind it. min is set to 1 there, but extending the solution for cases when min > 1 shouldn’t be too difficult.

1 Like

It is totally ok to research around and use math formulae that you find in your research. Learning how to come up with those types of things is a different type of training that is just as hard as learning how to code.

1 Like

Ok, so it’s not just an equation someone just came up with on the fly, it’s legit Math lol. I was wondering because it fits the algorithm so perfectly.

1 Like

this broke it down perfectly! Thanks so much