Program to check if N is a Centered heptagonal number
Last Updated :
19 Sep, 2022
Given an integer N, the task is to check if it is a Centered heptagonal number or not.
Centered heptagonal number is centered figure number that represents a heptagon with dot in center and all other dot surrounding in heptagonal form..The first few Centered heptagonal number are 1, 8, 22, 43, 71, 106, 148, …
Examples:
Input: N = 8
Output: Yes
Explanation:
8 is the Second Centered heptagonal number.
Input: 20
Output: No
Explanation:
20 is not a Centered heptagonal number.
Approach:
To solve the problem mentioned above we have to know that the Kth term of the Centered heptagonal number is given as:
As we have to check that the given number can be expressed as a Centered heptagonal number or not. This can be checked by generalizing the equation as:
=>
=>
Finally, check the value of computation using this formula if it is an integer, if yes then it means that N is a Centered heptagonal number.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isCenteredheptagonal( int N)
{
float n = (7 + sqrt (56 * N - 7)) / 14;
return (n - ( int )n) == 0;
}
int main()
{
int n = 8;
if (isCenteredheptagonal(n)) {
cout << "Yes" ;
}
else {
cout << "No" ;
}
return 0;
}
|
Java
import java.lang.Math;
class GFG
{
public static boolean isCenteredheptagonal( int N)
{
double n = ( 7 + Math.sqrt( 56 * N - 7 )) / 14 ;
return (n - ( int )n) == 0 ;
}
public static void main(String[] args)
{
int n = 8 ;
if (isCenteredheptagonal(n))
{
System.out.println( "Yes" );
}
else
{
System.out.println( "No" );
}
}
}
|
Python3
import math
def isCenteredheptagonal(N):
n = ( 7 + math.sqrt( 56 * N - 7 )) / 14
return (n - int (n)) = = 0
n = 8
if (isCenteredheptagonal(n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG{
static bool isCenteredheptagonal( int N)
{
double n = (7 + Math.Sqrt(56 * N - 7)) / 14;
return (n - ( int )n) == 0;
}
static public void Main ()
{
int n = 8;
if (isCenteredheptagonal(n))
{
Console.Write( "Yes" );
}
else
{
Console.Write( "No" );
}
}
}
|
Javascript
<script>
function isCenteredheptagonal(N)
{
let n = (7 + Math.sqrt(56 * N - 7)) / 14;
return (n - parseInt(n)) == 0;
}
let n = 8;
if (isCenteredheptagonal(n)) {
document.write( "Yes" );
}
else {
document.write( "No" );
}
</script>
|
Time Complexity: O(logN)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...