Add sequence of numbers in Javascript

Asked

Viewed 740 times

6

Let’s assume that the user type the value 40391, so I need to add incrementally all values from 1 up to 40390, which results in the value 815696245.

Today I do it with a simple for but I realized that the performance is not the best... Is there any way to make it more performatic ?

1 answer

8


Yes, just use a formula.

resultado = n(n+1)/2

See working:

var num = 40391;
var res = (num * (num - 1))/2; /*  adaptado o "-1" para o enunciado da pergunta  */
                               /*  que diz que input 40391 resulta em 815696245  */

document.write(res);


Out of curiosity, this sequence generates what we call a "triangular number":

Ilustração dos números triangulares

Further reading:

https://oeis.org/A000217

https://en.wikipedia.org/wiki/Triangular_number

Browser other questions tagged

You are not signed in. Login or sign up in order to post.