📜  程序检查N是否为十二边形数

📅  最后修改于: 2021-04-24 20:14:15             🧑  作者: Mango

给定数字N ,任务是检查N是否为十二边形数。如果数字N是十二边形数字,则打印“是”,否则打印“否”

例子:

方法:

1.十二边形数的第K项为
K^{th} Term = 5*K^{2} - 4*K

2.由于我们必须检查给定的数字是否可以表示为十二边形数。可以检查如下:

3.如果使用上述公式计算的K的值为整数,则N为十二边形数。

4.否则,数字N不是十二边形数字。

下面是上述方法的实现:

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


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to check if number N
// is a dodecagonal number or not
static boolean isdodecagonal(int N)
{
    float n = (float) ((4 + Math.sqrt(20 * N +
                                      16)) / 10);
 
    // Condition to check if the
    // N is a dodecagonal number
    return (n - (int)n) == 0;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given Number
    int N = 12;
 
    // Function call
    if (isdodecagonal(N))
    {
        System.out.print("Yes");
    }
    else
    {
        System.out.print("No");
    }
}
}
 
// This code is contributed by sapnasingh4991


Python3
# Python3 program for the above approach
import numpy as np
 
# Function to check if number N
# is a dodecagonal number or not
def isdodecagonal(N):
 
    n = (4 + np.sqrt(20 * N + 16)) / 10
 
    # Condition to check if the
    # N is a dodecagonal number
    return (n - int(n)) == 0
 
# Driver Code
N = 12
 
# Function call
if (isdodecagonal(N)):
    print("Yes")
else:
    print("No")
 
# This code is contributed by PratikBasu


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


Javascript


输出:
Yes

时间复杂度: O(1)

辅助空间: O(1)