![]() |
VOOZH | about |
Given a series and a number n, the task is to find the sum of its first n terms. Below is the series:
2, 5, 13, 35, 97, ...
Examples:
Input: N = 2 Output: 7 The sum of first 2 terms of Series is 2 + 5 = 7 Input: N = 4 Output: 55 The sum of first 4 terms of Series is 2 + 5 + 13 + 35 = 55
Approach: From this given series we find it is the sum of the Two GP series with common ratios 2, 3.
Sn = 2 + 5 + 13 + 35 + 97 ... + upto nth term
Sn = (2^0 + 3^ 0) + (2^1 + 3^1) + (2^2 + 3^2) + (2^3 + 3^3)+ (2^4 + 3^4) …… + upto nth term
Sn = (2^0 + 2^1 + 2^2 + 2^3 + 2^4 ... + upto nth term) + ( 3^0 + 3^1 + 3^2 + 3^3 …… + unto nth term )
Since We know that the sum of n terms of the GP is given by the following formula:
Below is the implementation of the above approach:
Sum = 55
Time Complexity: O(log n)
Auxiliary Space: O(1), As constant extra space is used.