C++ program to find n-th term of series 3, 9, 21, 41, 71…

C++Server Side ProgrammingProgramming

In this problem, we are given an integer N. The task is to find the n-th term in series 3, 9, 21, 41, 71...

Let’s take an example to understand the problem,

Input

N = 7

Output

169

Explanation

The series is 3, 9, 21, 41, 71, 169...

Solution Approach

A simple solution to the problem is by finding the general term of the series. The general term can be found by observing the series a bit. It is,

$$T(N) = \sum n^{2} + \sum n + 1$$

We can directly use the formula for the sum of square of first n natural numbers, first n natural number and then add the three values. At last return the resultant value,

$$T(N)=\left(\frac{n*(n+1)*(2n+1)}{6}\right)+\left(\frac{n*(n+1)}{2}\right)+1$$

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
int findNthTerm(int n) {
   return ((((n)*(n + 1)*(2*n + 1)) / 6) + (n * (n + 1) / 2) + 1);
}
int main() {
   int N = 12;
   cout<<"The "<<N<<"th term of the series is "<<findNthTerm(N);
   return 0;
}

Output

The 12th term of the series is 729
raja
Published on 13-Mar-2021 12:25:00
Advertisements