给定两个整数N和K ,任务是检查N是否可以表示为K个不同的正整数之和。
例子:
Input: N = 12, K = 4
Output: Yes
N = 1 + 2 + 4 + 5 = 12 (12 as sum of 4 distinct integers)
Input: N = 8, K = 4
Output: No
方法:考虑序列1 + 2 + 3 +…+ K ,它具有恰好K个不同的整数,且具有最小可能的和,即Sum =(K *(K – 1))/ 2 。现在,如果N <萨姆那么它不可能表示N为K不同的正整数的和,但如果N≥萨姆然后任意整数发言权X≥0可以被添加到求和,以产生等于N,即1 + 2的总和+ 3 +…+(K – 1)+(K + X)确保存在正好K个不同的正整数。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function that returns true if n
// can be represented as the sum of
// exactly k distinct positive integers
bool solve(int n, int k)
{
// If n can be represented as
// 1 + 2 + 3 + ... + (k - 1) + (k + x)
if (n >= (k * (k + 1)) / 2) {
return true;
}
return false;
}
// Driver code
int main()
{
int n = 12, k = 4;
if (solve(n, k))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java implementation of the approach
import java.io.*;
class GFG {
// Function that returns true if n
// can be represented as the sum of
// exactly k distinct positive integers
static boolean solve(int n, int k)
{
// If n can be represented as
// 1 + 2 + 3 + ... + (k - 1) + (k + x)
if (n >= (k * (k + 1)) / 2) {
return true;
}
return false;
}
// Driver code
public static void main(String[] args)
{
int n = 12, k = 4;
if (solve(n, k))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by anuj_67..
Python3
# Python 3 implementation of the approach
# Function that returns true if n
# can be represented as the sum of
# exactly k distinct positive integers
def solve(n,k):
# If n can be represented as
# 1 + 2 + 3 + ... + (k - 1) + (k + x)
if (n >= (k * (k + 1)) // 2):
return True
return False
# Driver code
if __name__ == '__main__':
n = 12
k = 4
if (solve(n, k)):
print("Yes")
else:
print("No")
# This code is contributed by
# Surendra_Gangwar
C#
// C# implementation of the approach
using System;
class GFG
{
// Function that returns true if n
// can be represented as the sum of
// exactly k distinct positive integers
static bool solve(int n, int k)
{
// If n can be represented as
// 1 + 2 + 3 + ... + (k - 1) + (k + x)
if (n >= (k * (k + 1)) / 2) {
return true;
}
return false;
}
// Driver code
static public void Main ()
{
int n = 12, k = 4;
if (solve(n, k))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by ajit.
PHP
= ($k * ($k + 1)) / 2) {
return true;
}
return false;
}
// Driver code
$n = 12;
$k = 4;
if (solve($n, $k))
echo "Yes";
else
echo "No";
// This code is contributed by ihritik
?>
Javascript
输出:
Yes