In this tutorial, you’ll learn how to write a JavaScript program to find sum of N numbers. Sum of N numbers means sum of numbes from 1 to n (n can be 100, 200 etc.)

Traditional Approach To Find Sum Of N Numbers

Let’s start by writing a simple JavaScript function which will loop through numbers from 1to N and calculate the sum. Here is how it looks :

/*
** Method to Find Sum of N Numbers
*/
function findSum(n) {
  let result = 0;
  for(let i = 1; i <= n; i++) {
    result = result + i;
  }
  return result
}

let n = 10;
console.log(`Sum of numebers from 1 to ${n} is ${findSum(n)}`)

As seen in the above, you iterated from 1 to number N and added the numbers to get the sum. The problem with the above implementation is that as the number gets bigger, so does the number of iterations.

Mathematical Approach To Find Sum Of N Numbers

Using a mathematical approach to find the sum of N numbers may completely remove the use of for loop. Let’s try to address the above problem from a mathematical approach.

The problem that you are trying to solve is :

1 + 2 + 3 + 4 + 5 + 6 + …….. + n

Let’s assume the sum of the above series to be sum.

sum = 1 + 2 + 3 + 4 + 5 + 6 + …….. + n ——— eq-1

Now let’s reverse the series, and add the numbers backwards which will also give the same sum.

sum = n + (n-1) + (n-2) + (n-3) + (n-4) + ……. + 1 ——- eq-2

Let’s add the above eq-1 and eq-2 equations.

2(sum) = (n+1) + (n+1) + (n+1) + (n+1) + ……. (n+1)

2(sum) = n times (n+1)

sum = (n times (n+1)) / 2

You can use the above formula to find the sum of N numbers. Now let’s write the JavaScript program which implements the above formula.

function findSumWithFormula(n) {
  return (n * (n + 1)) / 2 
}

let n = 10;
console.log(`Sum of numbers from 1 to ${n} is ${findSumWithFormula(n)}`);

Wrapping It Up

In this tutorial, you learnt about two ways to implement the sum of N numbers using JavaScript. Do let us know your thoughts in the comments below.