📜  程序检查N是否为星号

📅  最后修改于: 2021-04-23 06:55:23             🧑  作者: Mango

给定整数N ,任务是检查它是否为星号。

例子:

方法:

  1. 星号的第K项为
    K^{th} Term = 6*K*(K-1) + 1
  2. 因为我们必须检查给定的数字是否可以表示为星号。可以按以下方式检查–
  1. 最后,检查使用此公式计算的值是整数,这意味着N是星号。

下面是上述方法的实现:

C++
// C++ implementation to check that
// a number is a star number or not
 
#include 
 
using namespace std;
 
// Function to check that the
// number is a star number
bool isStar(int N)
{
    float n
        = (6 + sqrt(24 * N + 12))
          / 6;
 
    // Condition to check if the
    // number is a star number
    return (n - (int)n) == 0;
}
 
// Driver Code
int main()
{
    int i = 13;
 
    // Function call
    if (isStar(i)) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
    return 0;
}


Java
// Java implementation to check that
// a number is a star number or not
import java.io.*;
import java.util.*;
 
class GFG{
     
// Function to check that the
// number is a star number
static boolean isStar(int N)
{
    double n = (6 + Math.sqrt(24 * N + 12)) / 6;
 
    // Condition to check if the
    // number is a star number
    return (n - (int)n) == 0;
}
     
// Driver code
public static void main(String[] args)
{
    int i = 13;
 
    // Function call
    if (isStar(i))
    {
        System.out.println("Yes");
    }
    else
    {
        System.out.println("No");
    }
}
}
 
// This code is contributed by coder001


Python3
# Python3 implementation to check that
# a number is a star number or not
import math
 
# Function to check that the
# number is a star number
def isStar(N):
     
    n = (math.sqrt(24 * N + 12) + 6) / 6
     
    # Condition to check if the
    # number is a star number
    return (n - int(n)) == 0
     
# Driver Code
i = 13
 
# Function call
if isStar(i):
    print("Yes")
else:
    print("No")
 
# This code is contributed by ishayadav181


C#
// C# implementation to check that
// a number is a star number or not
using System;
 
class GFG{
     
// Function to check that the
// number is a star number
static bool isStar(int N)
{
    double n = (6 + Math.Sqrt(24 * N + 12)) / 6;
 
    // Condition to check if the
    // number is a star number
    return (n - (int)n) == 0;
}
     
// Driver code
public static void Main()
{
    int i = 13;
 
    // Function call
    if (isStar(i))
    {
        Console.WriteLine("Yes");
    }
    else
    {
        Console.WriteLine("No");
    }
}
}
 
// This code is contributed by Code_Mech


Javascript


输出:
Yes