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.
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