Program to check if N is a Concentric Hexagonal Number
Given an integer N, the task is to check if N is a Concentric Hexagonal Numbers or not. If the number N is a Concentric Hexagonal Number then print “Yes” else print “No”.
Concentric Hexagonal Numbers are the number sequence forms a pattern with concentric hexagons, and the numbers denote the number of points required after the N-th stage of the pattern. The first few concentric hexagonal numbers are 0, 1, 6, 13, 24, 37, 54, 73, 96, 121 …
Examples:
Input: N = 6
Output: Yes
Explanation: Third Concentrichexagonal number is 6.
Input: N = 20
Output: No
Approach:
- The Kth term of the Concentric hexagonal number is given as:
Kth Term = (3 * K * K) / 2
- As we have to check that the given number can be expressed as a Concentric hexagonal number or not. This can be checked as:
Here, Kth Term = N => (3 * K * K) / 2 = N => 3 * K * K – 2 * N = 0 The positive root of this equation is: K = sqrt((2 * N )/3)
- If the value of K calculated using the above formula is an integer, then N is a Concentric Hexagonal Number.
- Else the number N is not a ConcentricHexagonal Number.
C++
#include <bits/stdc++.h>
using namespace std;
bool isConcentrichexagonal( int N)
{
float n = sqrt ((2 * N) / 3);
return (n - ( int )n) == 0;
}
int main()
{
int N = 6;
if (isConcentrichexagonal(N)) {
cout << "Yes" ;
}
else {
cout << "No" ;
}
return 0;
}
|
Java
class GFG{
static boolean isConcentrichexagonal( int N)
{
float n = ( float ) Math.sqrt(( 2 * N) / 3 );
return (n - ( int )n) == 0 ;
}
public static void main(String[] args)
{
int N = 6 ;
if (isConcentrichexagonal(N))
{
System.out.print( "Yes" );
}
else
{
System.out.print( "No" );
}
}
}
|
Python3
import math
def isConcentrichexagonal(N):
n = math.sqrt(( 2 * N) / 3 )
return (n - int (n)) = = 0
N = 6
if isConcentrichexagonal(N):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG{
static bool isConcentrichexagonal( int N)
{
float n = ( float ) Math.Sqrt((2 * N) / 3);
return (n - ( int )n) == 0;
}
public static void Main()
{
int N = 6;
if (isConcentrichexagonal(N))
{
Console.Write( "Yes" );
}
else
{
Console.Write( "No" );
}
}
}
|
Javascript
function isConcentrichexagonal(N)
{
let n = Math.sqrt((2 * N) / 3)
return (n - Math.floor(n)) == 0
}
let N = 6
if (isConcentrichexagonal(N))
console.log( "Yes" )
else
console.log( "No" )
|
Time complexity: O(logN) for given n, as it is using inbuilt sqrt function
Auxiliary space: O(1)
Last Updated :
20 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...