📜  程序检查N是否为中心三角数

📅  最后修改于: 2021-05-06 09:23:30             🧑  作者: Mango

给定一个整数N ,任务是检查它是否是一个居中三角数。

例子:

方法:

  • 第K中心三角数可表示为:
    K^{th} Term = \frac{3*K^{2} + 3*K + 2}{2}
  • 为了检查给定数字N是否可以表示为中心三角数,我们需要检查是否\frac{-3 + \sqrt{24*N - 15}}{6}  是否给出整数。

下面是上述方法的实现:

C++
// C++ implementation to check
// whether a given number is a
// Centered triangular number or not
#include 
using namespace std;
 
// Function to check if the
// number is a Centered
// Triangular Number
bool isCenteredtriangular(int N)
{
    float K = (-3
               + sqrt(24 * N - 15))
              / 6;
 
    // Condition for K to be
    // an integer
    return (K - (int)K) == 0;
}
 
// Driver Code
int main()
{
    int N = 85;
    if (isCenteredtriangular(N)) {
        cout << "Yes";
    }
    else {
        cout << "No";
    }
    return 0;
}


Java
// Java implementation to check that
// a number is a centered triangular
// number or not
import java.lang.Math;
 
class GFG{
     
// Function to check that the number
// is a centered triangular number
public static boolean isCenteredTriangular(int N)
{
    double K = (-3 + Math.sqrt(24 * N - 15)) / 6;
 
    // Condition to check if the number
    // is a centered triangular number
    return (K - (int)K) == 0;
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 85;
 
    // Function call
    if (isCenteredTriangular(N))
    {
        System.out.println("Yes");
    }
    else
    {
        System.out.println("No");
    }
}
}
 
// This code is contributed by ShubhamCoder


Python3
# Python3 implementation to check
# whether a given number is a
# Centered triangular number or not
import math
 
# Function to check if the
# number is a Centered
# Triangular Number
def isCenteredtriangular(N):
     
    K = (-3 + math.sqrt(24 * N - 15)) / 6
     
    # Condition for K to be
    # an integer
    if (K - int(K)) == 0:
        return True
         
    return False
 
# Driver Code
 
# Given Number
N = 85
 
# Function call
if (isCenteredtriangular(N)):
    print("Yes")
else:
    print("No")
 
# This code is contributed by shubhamsingh10


C#
// C# implementation to check whether
// a given number is a centered
// triangular number or not
using System;
 
class GFG{
 
// Function to check if the number
// is a centered triangular number
static bool isCenteredtriangular(int N)
{
    double K = (-3 + Math.Sqrt(24 * N - 15)) / 6;
     
    // Condition for K to be
    // an integer
    return (K - (int)K) == 0;
}
     
// Driver Code
static public void Main ()
{
    int N = 85;
    if (isCenteredtriangular(N))
    {
        Console.Write("Yes");
    }
    else
    {
        Console.Write("No");
    }
}
}
 
// This code is contributed by shubhamsingh10


Javascript


输出:
Yes