n’th Pentagonal Number in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the n-th pentagonal number.

A pentagonal number is a number represented as dots or pebbles arranged in the shape of a regular polygon. Refer to the wiki for better understanding.

The n-th pentagonal number is (3 * n * n - n) / 2.

The series of pentagonal numbers are 1, 5, 12, 22, 35, 51, 70, 92...

Algorithm

  • Initialise the number n.
  • Use the formula to find the n'th pentagonal number.
  • Print the resultant number.

Implementation

Following is the implementation of the above algorithm in C++

#include<bits/stdc++.h>

using namespace std;

int getNthPentagonalNumber(int n) {
   return (3 * n * n - n) / 2;
}
int main() {
   int n = 7;
   cout << getNthPentagonalNumber(n) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

70
raja
Published on 29-Jun-2021 09:42:20
Advertisements