Direct Formula Approach

In this approach we will use direct formula to find nth term of G.P. The formula for calculating nth term of G.P. is an = a1 × r(n-1) . We will define the function which will return the nth term of G.P. by using its formula.

Syntax:

an = a1  × r(n-1) 

Parameters:

  • an: It represents the nth term of G.P.
  • a1: It is the first term of G.P.
  • r : It is the common ration of G.P.
  • n: It is the number of term which we are calculating.

Example: To demonstrate finding nth terms of the G.P. series using the function which uses nth term formula to find nth terms of an G.P. series to print the result.

Javascript
function nthTermGP(firstTerm, commonRatio, n) {
    return firstTerm * Math
        .pow(commonRatio, n - 1);
}
const firstTerm = 4;
const commonRatio = 2;

const n = 6;

const nthTerm = nthTermGP(firstTerm, commonRatio, n);
console.log("The", n + "th term of the G.P. is:", nthTerm);

Output
The 6th term of the G.P. is: 128

Time Complexity : O(logn), we are using power inbuilt function

Space Complexity : O(1) , constant space



JavaScript Program for nth Term of Geometric Progression

In this article, we are going to learn how to find the nth term of Geometric Progression using JavaScript. We will see different approaches that will return the nth term of G.P. 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 different approaches to finding the nth term of G.P. in Javascript:

Table of Content

  • Iterative Approach
  • Recursive Approach
  • Direct Formula Approach

Similar Reads

Iterative Approach

In this approach, we define an iterative function. We initialize nthTerm as a variable with the value of the first term a. We will traverse the loop from second term to n term and in each iteration, multiply term by the common ratio r. After loop completes we will return nth term of G.P.Example: To demonstrate finding nth terms of the G.P. series using iterative function which uses loop to traverse from 2 until n reaches to print the result....

Recursive Approach

In this approach we will define a recursive function. This function stops( i.e. base case) when n is equal to 1 it return first term i.e. a . If n is greater than 1, recursively call the function with the same first term a, common ratio r, and n – 1 as the term number. Multiply the result of the recursive call by the common ratio r. Return the result after recursive call stops....

Direct Formula Approach

In this approach we will use direct formula to find nth term of G.P. The formula for calculating nth term of G.P. is an = a1 × r(n-1) . We will define the function which will return the nth term of G.P. by using its formula....