A number loop passed to the function
function somaNumero(numero) {
var total = 0;
for(var i = 1; i <= numero; i++){
total += i;
}
return total;
}
//chama a função passando o numero
console.log(somaNumero(5));
The problem with the above implementation is that as the number increases, so does the number of iterations.
Using a mathematical approach to find the sum of N numbers can completely remove the use of the loop for. Let’s try to solve the above problem with a mathematical approach.
1 + 2 + 3 + 4 + 5 + 6 + …… .. + n
Let’s assume that the sum of the series above is total .
total = 1 + 2 + 3 + 4 + 5
Now let’s reverse the series and add the numbers backwards, which will also give the same total.
total = n + (n-1) + (n-2) + (n-3) + (n-4)
Let’s add up the two totals
total + total = (n + 1) + ((n-1) + 2) + ((n-2) + 3) + ((n-3) + 4) + ((n-4) + 5)
2total = (n+1) + (n+1)+ (n+1)+ (n+1)+ (n+1)
2total = n(n+1)
total = (n(n+1))/2
or (number * (number + 1)) / 2
Upshot
function somaNumero(numero) {
return (numero * (numero + 1)) / 2
}
console.log(somaNumero(5));
For those who know what an Arithmetic Progression - PA , just note that the formula of the sum of the n first terms of PA (a1,a2,A3,...,an) is given by
Sn=a1+a2+...+ an=((a1+an) n)/2
Since (1,2,3,4,...,n) is a PA of ratio 1, it follows that the sum of n
first terms is given by:
(1+n)⋅n
_________
2
total = ((n+1) n)/2
Ever thought of a loop?
– anonimo
Marcelinha, the sum of Gauss to determine the sum of all natural up to a certain number is given by
function somaNumero(n) {
 return (n * (n + 1)) /2;
}

console.log(somaNumero(5));
– Augusto Vasques
Read: What a mistake I made asking my question?
– Maniero
defined the variable number twice. You did not define the variable i. You did not pass the value in the function call Do like this, this line is negligible var number = i; therefore delete it. Change the i by number and change the sign - by the way + Call the function by passing the value console.log(summeNumber(5)); This solution is in the mathematical approach of my answer
– user60252