DEV Community

Cover image for Summing Numbers in JavaScript with Different Techniques.
Sudhanshu Gaikwad
Sudhanshu Gaikwad

Posted on

1

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.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay