How to use Direct Formula In Javascript
The sum of the infinite terms of a Geometric Progression series can also be calculated using the direct mathematical formula.
Syntax:
S ∞ = a/ (1-r) where ∣r∣ < 1
where, S∞ is the sum of infinite terms of G.P., a is the first term of G.P., r is the common ratio of G.P. (for calculating sum of infinite terms in G.P. the absolute value of the common ratio must be less than 1)
Example: The below code will explain the use of the mathematical formula to calculate the sum of the infinite terms of GP.
function sumOfInfiniteTermsGPFormula(a, r) {
if (Math.abs(r) >= 1) {
return "Sum of infinite terms does not exist (diverges)";
}
return a / (1 - r);
}
console.log(sumOfInfiniteTermsGPFormula(10, 0.8));
console.log(sumOfInfiniteTermsGPFormula(8, 0.5));
Output
50.000000000000014 16
Time Complexity : O(1), constant time
Space Complexity : O(1), constant space
JavaScript Program for Sum of Infinite Terms in Geometric Progression
Geometric Progression is a sequence of numbers whose next term is calculated by multiplying the current term with a fixed number known as the common ratio.
Below are the approaches to find the sum of infinite terms in a Geometric progression using JavaScript:
Table of Content
- Using Iterative Approach
- Using Recursive Approach
- Using Direct Formula