Program to Find the nth term of the series
Find the Nth term in a mixed geometric series where odd positions follow powers of 2 and even positions follow powers of 3.
Understand the Problem
Problem Statement
This series is a mixture of 2 series - all the odd terms in this series form a geometric series (powers of 2) and all the even terms form another geometric series (powers of 3). 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 to STDOUT.
You can assume that N will not exceed 30.
Constraints
- N is a positive integer
- 1 ≤ N ≤ 30
- Input must be read from standard input
- Output must be written to standard output
- Only the numeric result should be printed
Examples
162187Position 16 is even, so we calculate 3^(16/2 - 1) = 3^7 = 2187
1364Position 13 is odd, so we calculate 2^(13/2) = 2^6 = 64
Solution
#include <stdio.h>
#include <math.h>
int main() {
int n;
scanf("%d", &n);
if (n % 2 == 0) {
// Even position: power of 3
int power = n / 2 - 1;
printf("%d", (int)pow(3, power));
} else {
// Odd position: power of 2
int power = n / 2;
printf("%d", (int)pow(2, power));
}
return 0;
}1. Read integer N from standard input
2. Check if N is even or odd using modulo operator
3. For even positions: calculate 3^(N/2 - 1) using pow() function
4. For odd positions: calculate 2^(N/2) using pow() function
5. Print the result using printf()
6. Return 0 to indicate successful execution