Sum of n Natural Numbers in JavaScript
n(n+1)/2. A loop also works. / in JS already gives a float.
BeginnerLoop ProgramsExample 2 of 6
sum-of-n-natural-numbers.js
1// Method 1: Using for loop2let n = 10;3let sum = 0;45for (let i = 1; i <= n; i++) {6 sum += i;7}89console.log("Sum of first", n, "natural numbers:", sum);1011// Method 2: Using formula (n × (n + 1)) / 212let num = 10;13let sumFormula = (num * (num + 1)) / 2;14console.log("Using formula:", sumFormula);1516// Method 3: Using while loop17let number = 10;18let total = 0;19let counter = 1;2021while (counter <= number) {22 total += counter;23 counter++;24}2526console.log("Using while loop:", total);2728// Method 4: Using function29function sumNaturalNumbers(n) {30 let sum = 0;31 for (let i = 1; i <= n; i++) {32 sum += i;33 }34 return sum;35}3637console.log("Using function:", sumNaturalNumbers(10));3839// Method 5: Using reduce (functional approach)40function sumNaturalNumbersReduce(n) {41 return Array.from({length: n}, (_, i) => i + 1)42 .reduce((sum, num) => sum + num, 0);43}4445console.log("Using reduce:", sumNaturalNumbersReduce(10));
Output
Sum of first 10 natural numbers: 55 Using formula: 55 Using while loop: 55 Using function: 55 Using reduce: 55
What's going on
N=10 → 55. The formula is O(1). The loop is clearer until N is huge.
n <= 0 is a bad prompt. The formula still "works" for 0.