N-th Term Of GP

Easy
0/40
Average time to solve is 15m
240 upvotes
Asked in companies
MicrosoftDisney + HotstarCuemath

Problem statement

You are given the first term (A), the common ratio (R) and an integer N. Your task is to find the Nth term of the GP series.

The general form of a GP(Geometric Progression) series is A, A(R), A(R^2), A*(R^3) and so on where A is the first term of GP series

Note :

As the answer can be large enough, return the answer modulo 10^9 + 7.

Detailed explanation ( Input/output format, Notes, Images )
Input format :
The first line of input contains an integer T denoting the number of queries or test cases. 

The first line of every test case contains three single space-separated integers N, A, and R denoting the term of GP series required, the first term, and the common ratio respectively. 
Output format :
For each test case, print an integer denoting the Nth term of GP in a separate line. 
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10
1 <= N <= 10^8
0 <= A <= 50 
0 <= R <= 100

Time limit: 1 second
Sample input 1 :
1
5 3 2 
Sample output 1 :
48
Explanation :
For N=5, A=3, and R=2. The GP series will be 3, 6, 12, 24, 48, and so on. Thus, the 5th term will be 48.  
Sample input 2 :
2
4 1 2
6 2 1 
Sample output 2 :
8
2
Hint

We can observe that everything asked from us can be done as it is done manually. 

As the GP series is A, AR, A(R^2), A(R^3) and so on, we can find that the Nth term of GP by putting values into the formula:-

Nth term of GP = AR^(N-1). 

Approaches (2)
Brute force
  1. The idea is to use the formulae, Nth term of GP = A*R^(N-1).
  2. To calculate POW i.e R^(N-1) we will use a loop and the algorithm for the same will be as given below,
    • Initialise POW = 1
    • For N-1 number of times,
      • POW = POW * R
  3. Return A * POW.
Time Complexity

O(N) per test case where N is the required term of series.

 

In the worst case, we will be running a loop for N-1 times.

Space Complexity

O(1) per test case. 

 

In the worst case, only constant space is required.

Code Solution
(100% EXP penalty)
N-th Term Of GP
Full screen
Console