Program to find N-th term in the given series in C++



In this problem, we are given a number N. Our task is to create a program to find N-th term in the given series in C++.

Problem Description

To find the sum of the given series −

1, 1, 2, 3, 4, 9, 8, 27, 16, 81, 32, 243, 64, 729, 128, 2187, 256, ... NTerms

We will find the general term of the series.

Let’s take an example to understand the problem,

Example 1

Input

N = 6

Output

9

Example 2

Input

N = 13

Output

64

Solution Approach

To solve the problem, we need to carefully observe the series. As it is, a mixture series and these types of series are difficult to recognize initially but later it is easy to work with.

The series is a mixture series of the at type,

At even places, the index of the series is a series of powers of 3.

At odd places, the index of the series is a series of powers of 2.

The general term is derived as −

T_{N}=2^{N/2}, if N is odd.

3^{N/2}, if N is even.

Example

 Live Demo

#include <iostream>
#include <math.h>
using namespace std;
int findLCM(int a, int b) {
   int LCM = a, i = 2;
   while(LCM % b != 0) {
      LCM = a*i;
      i++;
   }
   return LCM;
}

int findNTerm(int N) {
   if(N%2 == 0){
      return pow(3, ((N-1)/2));
   }
   else
      return pow(2, (N/2));
}
int main() {
   int N = 9;
   cout<<N<<"th term of the series is "<<findNTerm(N)<<endl; N = 14; cout<<N<<"th term of the series is "<<findNTerm(N);
}

Output

9th term of the series is 16
14th term of the series is 729

Advertisements