给定数字N ,任务是确定是否可以通过使用总数N整数(如果可能)来制作具有完整图层的Pascal三角形,如果可能,请打印是,否则请打印否。
注意: Pascal三角形是二项式系数的三角形阵列。以下是帕斯卡三角形的前6行。
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
从最顶层开始的Pascal三角形中,有1个整数,在从下到上的每一层中,该层的大小都增加了1。
例子:
Input: N = 10
Output: Yes
Explanation:
You can use 1, 2, 3 and 4 integers to make first, second, third, and fourth layer of pascal’s triangle respectively and also N = 10 satisfy by using (1 + 2 + 3 + 4) integers on each layer = 10.
Input: N = 5
Output: No
Explanation:
You can use 1 and 2 integers to make first and second layer respectively and after that you have only 2 integers left and you can’t make 3rd layer complete as that layer required 3 integers.
方法:在这里,我们从第一层开始在每一层上都使用整数1、2、3,…,因此,只有在可以用1 + 2 +的总和表示N的情况下,才能使Pascal三角形完整。
- 前X个整数的总和由下式给出
- 当且仅当我们仅能通过使用N个整数来制作帕斯卡的三角形其中X必须是一个正整数。因此,我们必须检查x是否存在正整数值。
- 为了从第二步确定X的值,我们可以推导公式为:
- 如果X的值等于N的给定值,则可以使Pascal Triangle成为Pascal Triangle。否则,我们将无法制作Pascal Triangle。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check if Pascaltriangle
// can be made by N integers
void checkPascaltriangle(int N)
{
// Find X
double x = (sqrt(8 * N + 1) - 1) / 2;
// If x is integer
if (ceil(x) - x == 0)
cout << "Yes";
else
cout << "No";
}
// Driver Code
int main()
{
// Given number N
int N = 10;
// Function Call
checkPascaltriangle(N);
return 0;
}
Java
// Java program for the above approach
class GFG{
// Function to check if Pascaltriangle
// can be made by N integers
static void checkPascaltriangle(int N)
{
// Find X
double x = (Math.sqrt(8 * N + 1) - 1) / 2;
// If x is integer
if (Math.ceil(x) - x == 0)
System.out.print("Yes");
else
System.out.print("No");
}
// Driver Code
public static void main(String[] args)
{
// Given number N
int N = 10;
// Function call
checkPascaltriangle(N);
}
}
// This code is contributed by amal kumar choubey
Python3
# Python3 program for the above approach
import math
# Function to check if Pascaltriangle
# can be made by N integers
def checkPascaltriangle(N):
# Find X
x = (math.sqrt(8 * N + 1) - 1) / 2
# If x is integer
if (math.ceil(x) - x == 0):
print("Yes")
else:
print("No")
# Driver Code
# Given number N
N = 10
# Function call
checkPascaltriangle(N)
# This code is contributed by sanjoy_62
C#
// C# program for the above approach
using System;
class GFG{
// Function to check if Pascaltriangle
// can be made by N integers
static void checkPascaltriangle(int N)
{
// Find X
double x = (Math.Sqrt(8 * N + 1) - 1) / 2;
// If x is integer
if (Math.Ceiling(x) - x == 0)
Console.Write("Yes");
else
Console.Write("No");
}
// Driver Code
public static void Main(String[] args)
{
// Given number N
int N = 10;
// Function call
checkPascaltriangle(N);
}
}
// This code is contributed by amal kumar choubey
Javascript
Yes
时间复杂度: O(sqrt(N))
辅助空间: O(1)