Sum of numbers until n

OSCC · JavaScript, Math · Oct 22, 2020

Sums all the numbers between 1 and n.

  • Use the formula (n * (n + 1)) / 2 to get the sum of all the numbers between 1 and n.
const sumN = n => (n * (n + 1)) / 2;
sumN(100); // 5050

Recommended snippets

  • Euclidean distance

    JavaScript, Math

    Calculates the distance between two points in any number of dimensions.

  • Sum of powers in range

    JavaScript, Math

    Calculates the sum of the powers of all the numbers from start to end (both inclusive).

  • Greatest common divisor

    JavaScript, Math

    Calculates the greatest common divisor between two or more numbers/arrays.