Program to check if N is a Centered Hexagonal Number
Given an integer N, the task is to check if N is a Centered Hexagonal Number or not. If the number N is a Centered Hexagonal Number then print “Yes” else print “No”.
Centered hexagonal number are figurate numbers and are in the form of the Hexagon. The Centered Hexagonal number is different from Hexagonal Number because it contains one element at the center..The first few Centered hexagonal numbers are 1, 7, 19, 37, 61, 91, 127 …
Input: N = 7
Second Centered hexagonal number is 7.
Input: N = 20
- The Kth term of the Centered hexagonal number is given as
- As we have to check that the given number can be expressed as a Centered hexagonal number or not. This can be checked as:
- If the value of K calculated using the above formula is an integer, then N is a Centered Hexagonal Number.
- Else the number N is not a Centered Hexagonal Number.
Below is the implementation of the above approach:
Time Complexity: O(1)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.