Find the Sum of N Natural Numbers in Javascript

Find the Sum of N Natural Numbers in Javascript

We will discuss three methods to solve this problem using javascript

Introduction

Hi everyone today we find the sum of N Natural Numbers in javascript. let's discuss how to solve this problem statement. if you want to check out yesterday's problem click here.

The goal is to add up all the numbers that fall inside the range from 0 to the integer input "num," with an integer num serving as the upper limit. Here are a few techniques for adding all the integers in a certain range.

  • Method 1: Using for Loop

  • Method 2: Using Formula

  • Method 3: Using recursion

We’ll discuss the above-mentioned methods in detail in the sections below.

Method 1: Using for Loop

Algorithm

  • step 1: take the input number

  • step 2: take the sum variable and initialize it with zero

  • step 3: run a loop 0 to num+1 and then simply add all the numbers to the sum variable.

  • step 4: print the sum

Javascript code

// Using for loop
let n = 6;
let sum = 0;
for(let i=0;i<=n;i++){
    sum+=i;
}
console.log(sum)

Output

21

Method 2: Using Formula

Algorithm

  • step 1: take the number input

  • step 2: implement the formula as sum = num * (num +1)/2

  • step 3: store this sum in the result

  • step 4: print the result

Formula:

Formula to Find the Sum of N Integers

Sum = num * ( num + 1 ) / 2

Javascript code

//Using Formula for the Sum of Nth Term
let n1=10;
let result = n1 * (n1 + 1)/ 2;
console.log(result);

Output

55

Method 3: Using Recursion

Algorithm

  • step 1: take the input number n

  • step 2: Define a recursive function with the base case as num == 0.

  • step 3: Set the recursive step call as num + recursive sum (num-1).

  • step 4: Call the recursive function and print the value returned by the function.

Javascript code

//Using Recursion
let n = 5;

function getSum(n) {
  if (n === 0) {
    return n;
  }
  return n + getSum(n - 1);
}
console.log(getSum(n));

Output

15

Conclusion

So this article we solved the problem statement using javascript language. I hope you found this article helpful for your web development journey.

  • If you fill this article informative please like this article, if you have any suggestions please comment on this article, share it on social media and follow me on

  • Hashnode - Gaurav Patil

  • Twitter - @GauravYPatil