DEV Community

Cover image for Summing Numbers in JavaScript with Different Techniques.
zenixtech
zenixtech

Posted on

Summing Numbers in JavaScript with Different Techniques.

When given a number n, the goal is to find the sum of the firstn natural numbers. For example, if n is 3, we want to calculate 1 + 2 + 3, which equals 6.
1. Using a Mathematical Formula.
function fun1():

function fun1(n) {
    return n * (n + 1) / 2;
} 
console.log("Ex - 1 >>> ", fun1(3)); // Output: 6

Enter fullscreen mode Exit fullscreen mode

2. Using a Loop.
function fun2():

function fun2(n) {
    let sum = 0;

    for (var i = 0; i <= n; i++) {
        sum = sum + i;
        console.log(i);
    }

    return sum;
}

console.log("Ex - 2 >>> ", fun2(3)); // Output: 6

Enter fullscreen mode Exit fullscreen mode
  • This function uses a loop to sum the first n natural numbers.
  • It initialises a variable sum to 0.
  • The loop runs from 0 to n. In each iteration, it adds the current value of i to sum.
  • For n = 3, the loop runs as

  • i = 0, sum = 0 + 0 = 0

  • i = 1, sum = 0 + 1 = 1

  • i = 2, sum = 1 + 2 = 3

  • i = 3, sum = 3 + 3 = 6

This approach is straightforward and easy to understand but can be less efficient for very large n compared to the mathematical formula.

Both methods achieve the same result but in different ways.

  • The mathematical formula (fun1) is faster and more efficient.
  • The loop method (fun2) is simple and intuitive but might take longer for larger values of n.

3.Summing Using Nested Loops
function fun3():

function fun3(n) {
    let sum = 0;

    for (let i = 0; i <= n; i++) {
        for (let j = 0; j <= i; j++) {
            sum++;
        }
    }

    return sum;
}

console.log(fun3(3)); // Output: 10

Enter fullscreen mode Exit fullscreen mode
  • This function uses nested loops to count the sum.
  • It initialises a variable sum to 0.
  • The outer loop runs from 0 to n.
  • The inner loop runs from 0 to the current value of i in the outer loop.
  • For each iteration of the inner loop, sum is incremented by 1.

To understand how this works, let's break down the steps when n = 3:

  1. When i = 0:
  • j runs from 0 to 0 (1 iteration), so sum becomes 1.
  1. When i = 1:
  • j runs from 0 to 1 (2 iterations), so sum becomes 3.
  1. When i = 2:
  • j runs from 0 to 2 (3 iterations), so sum becomes 6.
  1. When i = 3:
  • j runs from 0 to 3 (4 iterations), so sum becomes 10.

So, sum goes through these steps:

Initial sum = 0
After i = 0, sum = 1
After i = 1, sum = 3
After i = 2, sum = 6
After i = 3, sum = 10

Therefore, fun3(3) returns 10, which is the total number of increments performed.

Top comments (0)