![]() |
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 ApproachIn 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.
Output The 7 th term of the geometric progression is 192
Space Complexity : O(1) , constant space Recursive ApproachIn 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. Example: To demonstrate finding nth terms of the G.P. series using recursive function which uses recursive calls till base case reaches to print the result.
Output The 7 th term of the geometric progression using recursive function is 192
Space Complexity : O(n) , n recursive calls are made. Direct Formula ApproachIn 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:
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.
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 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |