Open In App

JavaScript Program to Find the Sum of Natural Numbers

Last Updated : 24 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to find the sum of Natural Numbers. Given a number N and the task is to find the Sum of the first N Natural Numbers.

These are the following methods, to get the sum of natural numbers:

  • Using for Loop
  • Using Recursion
  • Using Mathematical formula

Examples:

Input : n = 3
Output: 6
Explanation: 1 + 2 + 3 = 6
Input : 5
Output: 15
Explanation: 1 + 2 + 3 + 4 + 5 = 15

JavaScript Program to Find the Sum of Natural Numbers using For Loop

In this approach, we will loop through each natural number and add the value to the sum variable.

Example: We will use the for loop to get the sum of 1st N natural numbers. The time complexity of this approach is O(N).

Javascript




// Javascript program to find sum of first
// n natural numbers.
function findSum(n) {
    let sum = 0;
    for (let i = 1; i <= n; i++)
        sum = sum + i;
    return sum;
}
  
// Driver code
const n = 5;
console.log(findSum(n));


Output

15

JavaScript Program to Find the Sum of Natural Numbers using Recursion

We could define recursion formally in simple words, that is, a function calling itself again and again until it doesn’t have left with it anymore.

Example: In this approach, we are using the recursion function to get the sum of the first N natural numbers.

Javascript




// Javascript program to find sum of first
// n natural numbers.
function findSum(n) {
    if (n !== 0)
        return n + findSum(n - 1);
    else
        return n;
}
  
// Driver code
const n = 5;
console.log(findSum(n));


Output

15

JavaScript Program to Find the Sum of Natural Numbers using Mathematical formula

In this approach, we will use the formula for finding the n natural number. This is the most optimized solution. The time complexity is O(1) which is constant.

Example: The formula to find the sum of the first N natural numbers is (N * (N + 1)) / 2.

Javascript




// Javascript program to find sum of first
// n natural numbers.
function findSum(n) {
    return n * (n + 1) / 2;
}
  
// Driver code
const n = 5;
console.log(findSum(n));


Output

15


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads