# Program to find N-th term of series 0, 2,1, 3, 1, 5, 2, 7, 3...in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

In this problem, we are given a number N. Our task is to create a Program to find N-th term of series 0, 2, 1, 3, 1, 5, 2, 7, 3...in C++.

Problem Description − We are given the Series −

0, 2, 1, 3, 1, 5, 2, 7, 3...N Term

To find the Nth term of this series, we will formula the general term of the series and then find the Nth term.

Let’s take an example to understand the problem,

Input − N = 7

Output − 2

## Solution Approach :

To solve the problem and find the general formula for the series. We need to closely observe the series as it has two different series inside it. This type of series is a bit confusing at the start but once you know that it’s a mixture series, you will find it easy to find the general term.

Here, there are two series’ one on even index and the other on the odd index. Let’s see them individually.

Even index series: 0, 1, 1, 2, 3, ….

Odd index series: 2, 3, 5, 7, …

Now, it must be clear to you that the even series is the Fibonacci series. And the odd series is a series of prime numbers.

So, the series is −

If N is odd, (N/2) index fibonacci series.

If N is Even, (N/2) index prime number.

## Program to illustrate the working of our solution,

#include<iostream>
using namespace std;
int findNthPrimeTerm(int n) {

int primeCount = 0;
for (int i = 2; ; i++) {
int isPrime = 1;
for (int j = 2; j <= (i/2); j++) {
if (i % j == 0) {
isPrime = 0;
break;
}
}
if (isPrime)
primeCount++;
if (primeCount == n) {
return i;
break;
}
}
return -1;
}
int FibonaciiNthTerm(int n)
{
int nthTerm = 1, last = 0;
int i;
if( n == 0)
return 0;
else if( n == 1)
return 1;
else{
for (i = 2; i <= n; i++) {
nthTerm += last;
last = nthTerm - last ;
}
return nthTerm;
}
}
int findNTerm(int N) {

if (N % 2 == 0)
return findNthPrimeTerm(N/2);
else {
return FibonaciiNthTerm(N/2);
}
}
int main()
{
int N = 13;
cout<<N<<"th term of the series is "<<findNTerm(N)<<endl;
N = 4;
cout<<N<<"th term of the series is "<<findNTerm(N);
return 0;
}

## Output:

13th term of the series is 8
4th term of the series is 3