Given an integer n, find the nth Pentagonal number. The first three pentagonal numbers are 1, 5, and 12 (Please see the below diagram).
The n'th pentagonal number Pn is the number of distinct dots in a pattern of dots consisting of the outlines of regular pentagons with sides up to n dots when the pentagons are overlaid so that they share one vertex [Source Wiki]
Examples :
Input: n = 1
Output: 1
Input: n = 2
Output: 5
Input: n = 3
Output: 12
In general, a polygonal number (triangular number, square number, etc) is a number represented as dots or pebbles arranged in the shape of a regular polygon. The first few pentagonal numbers are: 1, 5, 12, etc.
If s is the number of sides in a polygon, the formula for the nth s-gonal number P (s, n) is
nth s-gonal number P(s, n) = (s - 2)n(n-1)/2 + n
If we put s = 5, we get
n'th Pentagonal number Pn = 3*n*(n-1)/2 + n
Examples:
Pentagonal Number

Below are the implementations of the above idea in different programming languages.
C++
// C++ program for above approach
#include<bits/stdc++.h>
using namespace std;
// Finding the nth pentagonal number
int pentagonalNum(int n)
{
return (3 * n * n - n) / 2;
}
// Driver code
int main()
{
int n = 10;
cout << "10th Pentagonal Number is = "
<< pentagonalNum(n);
return 0;
}
// This code is contributed by Code_Mech
C
// C program for above approach
#include <stdio.h>
#include <stdlib.h>
// Finding the nth Pentagonal Number
int pentagonalNum(int n)
{
return (3*n*n - n)/2;
}
// Driver program to test above function
int main()
{
int n = 10;
printf("10th Pentagonal Number is = %d \n \n",
pentagonalNum(n));
return 0;
}
Java
// Java program for above approach
class Pentagonal
{
int pentagonalNum(int n)
{
return (3*n*n - n)/2;
}
}
public class GeeksCode
{
public static void main(String[] args)
{
Pentagonal obj = new Pentagonal();
int n = 10;
System.out.printf("10th petagonal number is = "
+ obj.pentagonalNum(n));
}
}
Python3
# Python program for finding pentagonal numbers
def pentagonalNum( n ):
return (3*n*n - n)/2
#Script Begins
n = 10
print ("10th Pentagonal Number is = ", pentagonalNum(n))
#Scripts Ends
C#
// C# program for above approach
using System;
class GFG {
static int pentagonalNum(int n)
{
return (3 * n * n - n) / 2;
}
public static void Main()
{
int n = 10;
Console.WriteLine("10th petagonal"
+ " number is = " + pentagonalNum(n));
}
}
// This code is contributed by vt_m.
PHP
<?php
// PHP program for above approach
// Finding the nth Pentagonal Number
function pentagonalNum($n)
{
return (3 * $n * $n - $n) / 2;
}
// Driver Code
$n = 10;
echo "10th Pentagonal Number is = ",
pentagonalNum($n);
// This code is contributed by ajit
?>
JavaScript
<script>
// Javascript program for above approach
function pentagonalNum(n)
{
return (3 * n * n - n) / 2;
}
// Driver code to test above methods
let n = 10;
document.write("10th petagonal"
+ " number is = " + pentagonalNum(n));
// This code is contributed by avijitmondal1998.
</script>
Output10th Pentagonal Number is = 145
Time Complexity: O(1) // since no loop or recursion is used the algorithm takes up constant time to perform the operations
Auxiliary Space: O(1) // since no extra array or data structure is used so the space taken by the algorithm is constant
Another Approach:
The formula indicates that the n-th pentagonal number depends quadratically on n. Therefore, try to find the positive integral root of N = P(n) equation.
P(n) = nth pentagonal number
N = Given Number
Solve for n:
P(n) = N
or (3*n*n - n)/2 = N
or 3*n*n - n - 2*N = 0 ... (i)
The positive root of equation (i)
n = (1 + sqrt(24N+1))/6
After obtaining n, check if it is an integer or not. n is an integer if n - floor(n) is 0.
C++
// C++ Program to check a
// pentagonal number
#include <bits/stdc++.h>
using namespace std;
// Function to determine if
// N is pentagonal or not.
bool isPentagonal(int N)
{
// Get positive root of
// equation P(n) = N.
float n = (1 + sqrt(24*N + 1))/6;
// Check if n is an integral
// value of not. To get the
// floor of n, type cast to int.
return (n - (int) n) == 0;
}
// Driver Code
int main()
{
int N = 145;
if (isPentagonal(N))
cout << N << " is pentagonal " << endl;
else
cout << N << " is not pentagonal" << endl;
return 0;
}
Java
// Java Program to check a
// pentagonal number
import java.util.*;
public class Main {
// Function to determine if
// N is pentagonal or not.
public static boolean isPentagonal(int N)
{
// Get positive root of
// equation P(n) = N.
float n = (1 + (float)Math.sqrt(24 * N + 1)) / 6;
// Check if n is an integral
// value of not. To get the
// floor of n, type cast to int.
return (n - (int)n) == 0;
}
// Driver Code
public static void main(String[] args)
{
int N = 145;
if (isPentagonal(N))
System.out.println(N + " is pentagonal ");
else
System.out.println(N + " is not pentagonal");
}
}
Python3
import math
# Function to determine if N is pentagonal or not.
def isPentagonal(N):
# Get positive root of equation P(n) = N
n = (1 + math.sqrt(24*N + 1))/6
# Check if n is an integral value or not.
# To get the floor of n, use the int() function
return (n - int(n)) == 0
# Driver code
if __name__ == "__main__":
N = 145
if isPentagonal(N):
print(N, "is pentagonal")
else:
print(N, "is not pentagonal")
C#
using System;
public class Program
{
// Function to determine if
// N is pentagonal or not.
public static bool IsPentagonal(int n)
{
// Get positive root of equation P(n) = N.
float x = (1 + MathF.Sqrt(24 * n + 1)) / 6;
// Check if x is an integral value or not
return MathF.Floor(x) == x;
}
public static void Main()
{
int n = 145;
if (IsPentagonal(n))
Console.WriteLine(n + " is pentagonal");
else
Console.WriteLine(n + " is not pentagonal");
// Pause the console so that we can see the output
Console.ReadLine();
}
}
// This code is contributed by divyansh2212
JavaScript
// js equivalent
// import math functions
function isPentagonal(N) {
// Get positive root of equation P(n) = N
let n = (1 + Math.sqrt(24 * N + 1)) / 6;
// Check if n is an integral value or not.
// To get the floor of n, use the Math.floor() function
return (n - Math.floor(n)) === 0;
}
// Driver code
let N = 145;
if (isPentagonal(N)) {
console.log(`${N} is pentagonal`);
} else {
console.log(`${N} is not pentagonal`);
}
Time Complexity: O(log n) //the inbuilt sqrt function takes logarithmic time to execute
Auxiliary Space: O(1) // since no extra array or data structure is used so the space taken by the algorithm is constant
Reference:
https://en.wikipedia.org/wiki/Polygonal_number
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read