📜  程序检查N是否为中心六边形

📅  最后修改于: 2021-04-23 17:54:43             🧑  作者: Mango

给定整数N ,任务是检查N是否为中心六边形。如果数字N是中心六边形,则打印“是”,否则打印“否”。

例子:

方法:

  • 中心六边形数的第K项为
    K^{th} Term = {3*K^{2} - 3*K + 2}
  • 因为我们必须检查给定的数字是否可以表示为中心六边形数字。可以检查为:
  • 如果使用上述公式计算的K值为整数,则N为中心六边形数。
  • 否则,数字N不是中心六边形数字。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check that the
// number is a Centered hexagonal number
bool isCenteredhexagonal(int N)
{
    float n
        = (3 + sqrt(12 * N - 3))
          / 6;
 
    // Condition to check if the
    // number is a Centered hexagonal number
    return (n - (int)n) == 0;
}
 
// Driver Code
int main()
{
    int N = 7;
 
    // Function call
    if (isCenteredhexagonal(N)) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
    return 0;
}


Java
// Java program for the above approach
class GFG{
 
// Function to check that the
// number is a Centered hexagonal number
static boolean isCenteredhexagonal(int N)
{
    float n = (float)((3 + Math.sqrt(12 * N - 3)) / 6);
 
    // Condition to check if the
    // number is a Centered hexagonal number
    return (n - (int)n) == 0;
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 7;
 
    // Function call
    if (isCenteredhexagonal(N))
    {
        System.out.print("Yes");
    }
    else
    {
        System.out.print("No");
    }
}
}
 
// This code is contributed by sapnasingh4991


Python3
# Python3 program for the above approach
import math
 
# Function to check that the number
# is a centered hexagonal number
def isCenteredhexagonal(N):
     
    n = (3 + math.sqrt(12 * N - 3)) / 6
     
    # Condition to check if the number
    # is a centered hexagonal number
    return (n - int(n)) == 0
 
# Driver Code
N = 7
 
if isCenteredhexagonal(N):
    print("Yes")
else :
    print("No")
 
# This code is contributed by ishayadav181


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to check that the number
// is a centered hexagonal number
static bool isCenteredhexagonal(int N)
{
    float n = (float)((3 + Math.Sqrt(12 * N -
                                     3)) / 6);
 
    // Condition to check if the number
    // is a centered hexagonal number
    return (n - (int)n) == 0;
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 7;
 
    // Function call
    if (isCenteredhexagonal(N))
    {
        Console.Write("Yes");
    }
    else
    {
        Console.Write("No");
    }
}
}
 
// This code is contributed by amal kumar choubey


Javascript


输出:
Yes