C++ program to find nth Term of the Series 1 2 2 4 4 4 4 8 8 8 8 8 8 8 8 …

C++Server Side ProgrammingProgramming

In this problem, we are given an integer N. Our task is to create a program to Find Nth term of series 1, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8…

Let’s take an example to understand the problem,

Input

N = 7

Output

4

Solution Approach

A simple approach to solve the problem is using a loop to find the term at the nth position. The terms will be updated by doubling after each iteration. And adding it to the term counter.

Program to illustrate the working of our solution,

Example

#include <iostream>
using namespace std;
int calcNthTerm(int N) {
   int termCounter = 0, termValue = 1;
   while (termCounter < N) {
      termCounter += k;
      termValue *= 2;
   }
   return termValue / 2;
}
int main() {
   int N = 10;
   cout<<N<<"th term of the series is "<<calcNthTerm(N);
   return 0;
}

Output

10th term of the series is 8

Efficient Approach

An efficient approach to solve the problem is by finding the general term of the series.

Here, are terms and their last index,
1 -> last index = 1.
2 -> last index = 3.
4 -> last index = 7.
8 -> last index = 15.
.
.
T(N) -> last index = 2*(T(N)) - 1
Also, T(N) is always of a power of 2, i.e. T(N) = 2m
2m lies in the series till the index 2m+1-1.

To find the term we can calculate the value of 2(m) - 1 using N.

This makes 2m - 1 < N.

2m - 1 < N
So, m < log2(N + 1)

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
#include <math.h>
using namespace std;
int calcNthTerm(int N) {
   return ( pow(2, (floor)(log(N + 1) / log(2)) ) ) ;
}
int main() {
   int N = 10;
   cout<<N<<"th term of the series is "<<calcNthTerm(N);
   return 0;
}

Output

10th term of the series is 8
raja
Published on 15-Mar-2021 10:35:12
Advertisements