0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Find Sum of N Natural Numbers

You can find the sum of n natural numbers in JavaScript using the formula sum = n * (n + 1) / 2 or by looping from 1 to n and adding each number.
📋

Examples

Input5
Output15
Input10
Output55
Input1
Output1
🧠

How to Think About It

To find the sum of the first n natural numbers, think of adding all numbers from 1 up to n. You can do this by either adding each number one by one or using a simple math formula that calculates the total quickly without adding each number.
📐

Algorithm

1
Get the input number n.
2
Use the formula sum = n * (n + 1) / 2 to calculate the sum.
3
Return or print the sum.
💻

Code

javascript
function sumOfNaturalNumbers(n) {
  return n * (n + 1) / 2;
}

const n = 10;
console.log("Sum of", n, "natural numbers is", sumOfNaturalNumbers(n));
Output
Sum of 10 natural numbers is 55
🔍

Dry Run

Let's trace the example where n = 5 through the code.

1

Input value

n = 5

2

Apply formula

sum = 5 * (5 + 1) / 2 = 5 * 6 / 2 = 30 / 2 = 15

3

Return result

sum = 15

nCalculationSum
55 * (5 + 1) / 215
💡

Why This Works

Step 1: Why use the formula?

The formula n * (n + 1) / 2 quickly calculates the sum without needing to add each number one by one.

Step 2: How the formula works

It pairs numbers from start and end (like 1 and n) which always add up to the same total, then multiplies by half the count.

Step 3: Efficiency

Using the formula makes the program faster and simpler compared to looping through all numbers.

🔄

Alternative Approaches

Using a loop
javascript
function sumOfNaturalNumbersLoop(n) {
  let sum = 0;
  for (let i = 1; i <= n; i++) {
    sum += i;
  }
  return sum;
}

const n = 10;
console.log("Sum using loop:", sumOfNaturalNumbersLoop(n));
This method is easy to understand but slower for large n because it adds each number one by one.
Using recursion
javascript
function sumOfNaturalNumbersRec(n) {
  if (n === 1) return 1;
  return n + sumOfNaturalNumbersRec(n - 1);
}

const n = 10;
console.log("Sum using recursion:", sumOfNaturalNumbersRec(n));
Recursion is elegant but can cause stack overflow for very large n and is less efficient than the formula.

Complexity: O(1) time, O(1) space

Time Complexity

Using the formula takes constant time because it performs a fixed number of operations regardless of n.

Space Complexity

The formula uses constant space since it only stores a few variables.

Which Approach is Fastest?

The formula approach is fastest and most efficient compared to looping or recursion, which take O(n) time.

ApproachTimeSpaceBest For
FormulaO(1)O(1)Fastest for any n
LoopO(n)O(1)Easy to understand, small n
RecursionO(n)O(n)Learning recursion, small n
💡
Use the formula n * (n + 1) / 2 for the fastest and simplest solution.
⚠️
Beginners often forget to include the +1 in the formula or use zero instead of one as the start of natural numbers.