The sum of the Numbers in a Given Interval 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 use various techniques to get the sum of all the numbers that fall inside the specified interval given the range as integer input. To do this, we just repeat the base interval and end interval iterations while continuously increasing the number. Here are a few Javascript language solutions to the aforementioned issue.
Method1: Using Brute Force
Method2: Using the Formula
Method3: Using Recursion
Method 1: Using Brute Force
In this method, we’ll use for loops to iterate through from the base interval to the upper interval meanwhile adding all the numbers to the sum variable.
Algorithm
step 1: take input of a and b. a is starting number and b is the ending number
step 2: take the sum variable and initialized it with zero
Step 3: Initiate a for loop from the range [a,b].
Step 4: Keep adding the value of the iterable variable to the sum variable.
step 5: Print the sum variable.
Javascript Code
//Using Brute Force
let a = 5;
let b = 10;
let sum = 0;
for(let i=a;i<=b;i++){
sum = sum + i;
}
console.log("The sum is "+ sum);
Output
The sum is 45
Method2: Using Formula
In this method, we’ll use a sequence and series formula to find the sum of n numbers in a series. Formula : N*(N+1)/2.
Algorithm
step 1: Initialize num1 and num2
step 2: Apply the given formula sum = b*(b+1)/2 – a*(a+1)/2 + a.
step 3: Print the sum variable as the output.
Formula
sum = b*(b+1)/2 – a*(a+1)/2 + a.
Javascript Code
//Using formula
let num1 = 2;
let num2 = 5;
let sum = num2 * (num2 + 1) / 2 - num1 * (num1 + 1) / 2 + num1;
console.log("The Sum is " + sum);
Output
The Sum is 14
Method3: Using Recursion
In this method, we’ll use recursion to iterate through and sum up all the numbers that lay in the given interval.
Algorithm
step 1: take input of a and b. a is starting number and b is the ending number
step 2: take the sum variable and initialized it with zero.
step 3: Define a recursive function with the base case as number1 == number2.
step 4: Set the recursive set call as num1+ function(sum,num1+1,num2).
step 5: print the returned value after calling the recursive functions.
Javascript Code
let a = 5;
let b = 10;
function getSum(sum, i, b) {
if (i > b) {
return sum;
}
return i + getSum(sum, i + 1, b);
}
console.log("The sum is " + getSum(0, a, b));
Output
The sum is 45
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