Check if given number is a Dodecahedral number

By | November 30, 2024

Given a number N, the task is to check if N is a dodecahedral Number –

Dodecahedral Number belongs to a figurate number and represents it dodecahedron. The first few dodecahedral numbers are 1, 20, 84, 220, 455, 816, 1330 …

Examples:

Input: N = 20
Output: Yes
Explanation: 20 is the second dodecahedral number

Input: N = 6
Output: No

Approach:

  1. The nth term of dodecahedral number is given by \frac{n * (3 * n – 1) * (3 * n – 2)}{2}
  2. Run a loop starting from 1, to find ith dodecahedral number.
  3. Check if ith term is equal to n or not. If equal return true
  4. If ith term is greater than n then return false
  5. else increment i and continue the loop

Below is the implementation of the above approach:

// C++ program for the above approach 
#include <bits/stdc++.h> 
using namespace std; 

// Function to check if the number N 
// is a dodecahedral number 
bool isDodecahedral(int N) 
{ 
    int i = 1;
    while(true)
    {
        // finding ith term
        int ith_term = i * (3 * i - 1) * (3 * i - 2) / 2; 
        // checking if the number N 
        // is a dodecahedral number 
        if(ith_term == N)
        {
            return true;
        }
        // if ith_term > N then
        // N is not a dodecahedral number
        if(ith_term > N)
        {
            return false;
        }
        // incrementing i
        i++;
    }
} 

// Driver Code 
int main() 
{ 
    // Given Number 
    int N = 20; 

    // Function call 
    if (isDodecahedral(N)) { 
        cout << "Yes"; 
    } 
    else { 
        cout << "No"; 
    } 
    return 0; 
}

Output:

Yes

Time complexity: O(N).

Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.