📜  程序检查N是否为十六进制数

📅  最后修改于: 2021-05-07 08:27:45             🧑  作者: Mango

给定整数N ,任务是检查N是否为十六进制数。如果数字N是十六进制数字,则打印“是”,否则打印“否”

例子:

方法:

1.十六进制数的第K项为
K^{th} Term = \frac{14*K^{2} - 12*K}{2}

2.由于我们必须检查给定的数字是否可以表示为十六进制数字。可以检查为:

3.如果使用上述公式计算的K值为整数,则N为十六进制数。

4.其他N不是十六进制数。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check if N is a
// hexadecagonal number
bool ishexadecagonal(int N)
{
    float n
        = (12 + sqrt(112 * N + 144))
          / 28;
 
    // Condition to check if the
    // number is a hexadecagonal number
    return (n - (int)n) == 0;
}
 
// Driver Code
int main()
{
    // Given Number
    int N = 16;
 
    // Function call
    if (ishexadecagonal(N)) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
    return 0;
}


Java
// Java program for the above approach
import java.lang.Math;
 
class GFG{
     
// Function to check if N is a
// hexadecagonal number
public static boolean ishexadecagonal(int N)
{
    double n = (12 + Math.sqrt(112 * N +
                               144)) / 28;
     
    // Condition to check if the
    // number is a hexadecagonal number
    return (n - (int)n) == 0;
}
     
// Driver code   
public static void main(String[] args)
{
         
    // Given number
    int N = 16;
     
    // Function call
    if (ishexadecagonal(N))
    {
        System.out.println("Yes");
    }
    else
    {
        System.out.println("No");
    }
}
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python3 program for the above approach
from math import sqrt
 
# Function to check if N is
# a hexadecagonal number
def ishexadecagonal(N):
 
    n = (12 + sqrt(112 * N + 144)) / 28;
 
    # Condition to check if the number
    # is a hexadecagonal number
    return (n - int(n)) == 0;
 
# Driver code
if __name__ == "__main__":
 
    # Given number
    N = 16;
 
    # Function call
    if (ishexadecagonal(N)):
        print("Yes");
    else:
        print("No");
     
# This code is contributed by AnkitRai01


C#
// C# program for the above approach
using System;
 
class GFG{
     
// Function to check if N is a
// hexadecagonal number
public static bool ishexadecagonal(int N)
{
    double n = (12 + Math.Sqrt(112 * N +
                             144)) / 28;
     
    // Condition to check if the
    // number is a hexadecagonal number
    return (n - (int)n) == 0;
}
     
// Driver code
public static void Main(string[] args)
{
         
    // Given number
    int N = 16;
     
    // Function call
    if (ishexadecagonal(N))
    {
        Console.Write("Yes");
    }
    else
    {
        Console.Write("No");
    }
}
}
 
// This code is contributed by rutvik_56


Javascript


输出:
Yes

时间复杂度: O(1)

辅助空间: O(1)