C++ program to find nth term of the series 5, 2, 13 41,...

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 5, 2, 19, 13, 41, 31, 71, 57…

Let’s take an example to understand the problem,

Input

N = 5

Output

41

Explanation

The series is − 5, 2, 19, 13, 41, …

Solution Approach

A simple approach to solve the problem is by using the general formula for the nth term of the series. The series has different formulas for even and odd values.

The Nth term is given by,

Nth term = (N-1)^2 + N, if N is even i.e N%2 == 0
Nth term = (N+1)^2 + N, if N is odd i.e N%2 != 0

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
int calcNthTerm(int N) {
   if (N % 2 == 0)
      return ( ( (N - 1)*( N - 1) ) + N ) ;
   return ( ( (N + 1)*( N + 1) ) + N ) ;
}
int main() {
   int N = 7;
   cout<<N<<"th term of the series is "<<calcNthTerm(N);
   return 0;
}

Output

6th term of the series is 258
raja
Published on 15-Mar-2021 10:43:21
Advertisements