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.

Javascript
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

Similar Reads

Using Iterative Approach

In this approach, we use the while loop to iterate continuously and add terms to the sum until convergence. In each iteration, we will add the current term to the sum and update the value of nTerm by multiplying it with the common ratio r....

Using Recursive Approach

In this approach, we will define a recursive function. This function stops when the absolute value of the current term becomes very small, indicating convergence. Else, we will recursively call the function and calculate the sum of the current term and the sum of subsequent terms by multiplying the current term by the common ratio r and adding it to the sum of subsequent terms....

Using Direct Formula

The sum of the infinite terms of a Geometric Progression series can also be calculated using the direct mathematical formula....