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 …
Examples:
Input: N = 7
Output: Yes
Explanation:
Second Centered hexagonal number is 7.
Input: N = 20
Output: No
Approach:
- 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:
C++
#include <bits/stdc++.h>
using namespace std;
bool isCenteredhexagonal( int N)
{
float n
= (3 + sqrt (12 * N - 3))
/ 6;
return (n - ( int )n) == 0;
}
int main()
{
int N = 7;
if (isCenteredhexagonal(N)) {
cout << "Yes" ;
}
else {
cout << "No" ;
}
return 0;
}
|
Java
class GFG{
static boolean isCenteredhexagonal( int N)
{
float n = ( float )(( 3 + Math.sqrt( 12 * N - 3 )) / 6 );
return (n - ( int )n) == 0 ;
}
public static void main(String[] args)
{
int N = 7 ;
if (isCenteredhexagonal(N))
{
System.out.print( "Yes" );
}
else
{
System.out.print( "No" );
}
}
}
|
Python3
import math
def isCenteredhexagonal(N):
n = ( 3 + math.sqrt( 12 * N - 3 )) / 6
return (n - int (n)) = = 0
N = 7
if isCenteredhexagonal(N):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG{
static bool isCenteredhexagonal( int N)
{
float n = ( float )((3 + Math.Sqrt(12 * N -
3)) / 6);
return (n - ( int )n) == 0;
}
public static void Main(String[] args)
{
int N = 7;
if (isCenteredhexagonal(N))
{
Console.Write( "Yes" );
}
else
{
Console.Write( "No" );
}
}
}
|
Javascript
<script>
function isCenteredhexagonal(N)
{
let n = parseInt((3 + Math.sqrt(12 * N - 3)) / 6);
return (n - parseInt(n)) == 0;
}
let N = 7;
if (isCenteredhexagonal(N))
{
document.write( "Yes" );
}
else
{
document.write( "No" );
}
</script>
|
Time Complexity: O(logN) because it is using inbuilt sqrt function
Auxiliary Space: O(1)
Last Updated :
18 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...