Sum of N-terms of geometric progression for larger values of N | Set 2 (Using recursion)


A Geometric series is a series with a constant ratio between successive terms. The first term of the series is denoted by a and the common ratio is denoted by r. The series looks like this:-  a, ar, ar^2, ar^3, ar^4,... .
The task is to find the sum of such a series mod M.

Examples:

Input:  a = 1, r = 2, N = 10000, M = 10000
Output:  8751

Input:  a = 1, r = 4, N = 10000, M = 100000
Output:  12501

Approach:

  1. To find the sum of series  a + ar + ar^2 + ar^3 + . . . . + ar^N we can easily take a as common and find the sum of  1 + r + r^2 + r^3 + . . . . + r^N and multiply it with a.
  2. Steps to find the sum of above series.

    • Here, it can be resolved that:
       [1 + r + r^2 + r^3 + . . . + r^(2*n+1)] = (1+r)*(1 + (r^2) + (r^2)^2 + (r^2)^3 + . . . + (r^2)^n) .
    • If we denote,
       Sum(r, n) = 1 + r + r^2 + r^3 + . . . . + r^N. then,
       Sum(r, 2 * n + 1) = (1 + r) * Sum(r^2, n). and,
       Sum(r, 2 * n) = 1 + (r * (1 + r) * Sum(r^2, n - 1)).



      This will work as our recursive case.

    • So, the Base cases are:

                   Sum(r, 0) = 1.
                   Sum(r, 1) = 1 + r.
      

Below is the implementation of the above approach.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to illustrate the program 
  
# Function to calculate the sum 
# recursively
def SumGPUtil (r, n, m):
      
    # Base cases
    if n == 0: return 1
    if n == 1: return (1 + r) % m
    
    # If n is odd
    if n % 2 == 1:
        ans = (1 + r) * SumGPUtil(r * r % m,
                                  (n - 1)//2,
                                  m)
    else:
        #If n is even
        ans = 1 + r * (1 + r) * SumGPUtil(r * r % m,
                                          n//2 - 1,
                                          m)
    
    return ans % m
  
# Function to print the value of Sum
def SumGP (a, r, N, M):
      
    answer = a * SumGPUtil(r, N, M)
    answer = answer % M
    print(answer)
  
#Driver Program
if __name__== '__main__':
  
    a = 1 # first element
    r = 4 # common diffrence
    N = 10000 # Number of elements
    M = 100000 # Mod value 
  
    SumGP(a, r, N, M)

chevron_right


Output:

12501

Time complexity: O(log N)

competitive-programming-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.