# Sum All Numbers in a Range - Better way?

Sum All Numbers in a Range - Better way?
0

Tell us what’s happening:

This code works, is there a more elegant solution? Is created a new array and using reduce to sumAll in the array better?

``````
function sumAll(arr) {

let total = 0;
for (let i = Math.min(...arr); i <= Math.max(...arr); i++){
total+= i;
}
}

sumAll([1, 4]);
``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36`.

For me if the code works it’s good to go. Maybe learn about big O notation if you want to write more efficient code.

1 Like

Look at the Get a Hint page for more solution options.

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution.

Thank you.

2 Likes

Thank you for the response.

Thank you, yes makes sense to blur it out. I love that you guys go that.

You can use the “sum of the first n terms of an Arithmetic Progression Sequence” equation.

Sn= n * (a1 + an) / 2

``````const sumAll = (arr) => {
let an = Math.max(...arr)
let a1 = Math.min(...arr)
let n = (an - a1) + 1;
return ((an + a1) * n)/2;
}
``````
1 Like