📜  程序检查N是否为六角数

📅  最后修改于: 2021-04-29 09:22:40             🧑  作者: Mango

给定数字N ,检查它是否为六角形。如果是,则打印“是”,否则输出“否”。

例子:

方法:要解决上述问题,我们必须注意,第n个六角形数由以下公式给出: H(n)= n *(2n – 1) 。该公式表明,第n个六边形数二次取决于n。因此,找到N = H(n)方程的正整数根。

因此,H(n)=第n个六角形数,N是给定的数。因此,求解以下方程式:

获得n的值后,检查它是否为整数,如果n – floor(n)为0 ,则n为整数

下面是上述方法的实现:

C++
// C++ Program to check
// if N is a Hexagonal Number
 
#include 
using namespace std;
 
// Function to check
// if number is hexagonal
bool isHexagonal(int N)
{
    float val = 8 * N + 1;
 
    float x = 1 + sqrt(val);
 
    // Calculate the value for n
    float n = (x) / 4;
 
    // Check if n - floor(n)
    // is equal to 0
    if ((n - (int)n) == 0)
        return true;
 
    else
        return false;
}
 
// Driver code
int main()
{
    int N = 14;
 
    if (isHexagonal(N) == true)
        cout << "Yes" << endl;
 
    else
        cout << "No" << endl;
 
    return 0;
}


Java
// Java program to check
// if N is a hexagonal number
import java.util.*;
 
class GFG {
 
// Function to check
// if number is hexagonal
static boolean isHexagonal(int N)
{
    float val = 8 * N + 1;
 
    float x = 1 + (float)Math.sqrt(val);
 
    // Calculate the value for n
    float n = (x) / 4;
 
    // Check if n - floor(n)
    // is equal to 0
    if ((n - (int)n) == 0)
        return true;
 
    else
        return false;
}
 
// Driver code
public static void main(String[] args)
{
    int N = 14;
 
    if (isHexagonal(N) == true)
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program to check
# if N is a hexagonal number
from math import sqrt
 
# Function to check
# if number is hexagonal
def isHexagonal(N):
     
    val = 8 * N + 1
    x = 1 + sqrt(val)
 
    # Calculate the value for n
    n = x / 4
 
    # Check if n - floor(n)
    # is equal to 0
    if ((n - int(n)) == 0):
        return True
    else:
        return False
 
# Driver code
if __name__ == '__main__':
     
    N = 14
     
    if (isHexagonal(N) == True):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by BhupendraSingh


C#
// C# program to check if
// N is a hexagonal number
using System;
 
class GFG{
 
// Function to check
// if number is hexagonal
static bool isHexagonal(int N)
{
    float val = 8 * N + 1;
    float x = 1 + (float)Math.Sqrt(val);
 
    // Calculate the value for n
    float n = (x) / 4;
 
    // Check if n - floor(n)
    // is equal to 0
    if ((n - (int)n) == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}
 
// Driver code
public static void Main(string[] args)
{
    int N = 14;
 
    if (isHexagonal(N) == true)
        Console.Write("Yes");
    else
        Console.Write("No");
}
}
 
// This code is contributed by rutvik_56


Javascript


输出:
No

时间复杂度: O(1)