Asked 5 months ago
0Comments
1 Views
Given Problem Statement !
Consider the following series: 1,1,2,3,4,9,8,27,16,81,32,243,64,729,128,2187... This series is a mixture of 2 series – all the odd terms in this series form a geometric series and all the even terms form yet another geometric series. Write a program to find the Nth term in the series. The value N in a positive integer that should be read from STDIN. The Nth term that is calculated by the program should be written to STDOUT. Other than value of n th term,no other character / string or message should be written to STDOUT. For example , if N=16, the 16th term in the series is 2187, so only value 2187 should be printed.
#include <iostream>
#include <cmath> // For pow function
using namespace std;
int main() {
int N;
cin >> N;
if (N % 2 == 1) {
// Odd-indexed term
int termIndex = (N / 2); // N/2 gives the 0-based index for odd terms
cout << pow(2, termIndex) << endl;
} else {
// Even-indexed term
int termIndex = (N / 2) - 1; // (N/2 - 1) gives the 0-based index for even terms
cout << pow(3, termIndex) << endl;
}
return 0;
}
N is the position of the term we're looking for in the combined series. For example:
Why we're using those index mappings:
Test Case: Let's say N = 10
Indeed, the 10th term (N = 10) is 81, which matches our calculation.
Let's break down why this works:
You can see that the exponent is always (N / 2) - 1 for the power-of-3 series.
Similarly, for the power-of-2 series (odd positions):
Here, the exponent is always N / 2 (integer division) for the power-of-2 series.
Let's break this down more clearly:
You're absolutely right to point this out. The even indices in the combined series give us the odd-looking series (powers of 3), while the odd indices give us the even-looking series (powers of 2).
This is why in the code:
Share