Add sequence of numbers in Javascript

6

Suppose the user types the value 40391, so I need to incrementally add all values from 1 to 40390, which results in the value 815696245.

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

    
asked by anonymous 02.09.2018 / 01:31

1 answer

7

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 the "triangular number":

FurtherReading:

  

link

  

link

    
02.09.2018 / 01:49