📌  相关文章
📜  检查是否存在给定总和的K个不同的正偶数整数

📅  最后修改于: 2021-04-18 02:42:23             🧑  作者: Mango

给定两个整数NK ,任务是查找是否存在K个不同的正偶数整数,以使它们的和等于给定数N。

例子:

方法:解决此问题的想法是观察到,如果N奇数,则不可能用K个偶数获得所需的N。如果N是偶数,则找到前K个偶数的和,如果它们的总和小于或等于N ,则打印“是”。否则,不存在K个和数等于N的偶数个偶数整数。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find if the sum
// of K even integers equals N
void isPossibleN(int N, int K)
{
 
    // If N is odd, then its impossible
    // to obtain N from K even numbers
    if (N % 2 == 1) {
        cout << "NO" << endl;
        return;
    }
 
    // Sum first k even numbers
    int sum = K * (K + 1);
 
    // If sum is less then equal to N
    if (sum <= N) {
        cout << "YES" << endl;
    }
 
    // Otherwise
    else {
        cout << "No" << endl;
    }
 
    return;
}
 
// Driver Code
int main()
{
 
    int N = 16;
    int K = 3;
 
    isPossibleN(N, K);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG
{
  
static void isPossibleN(int N, int K)
{
 
    // If N is odd, then its impossible
    // to obtain N from K even numbers
    if (N % 2 == 1) {
        System.out.println("NO");
        return;
    }
 
    // Sum first k even numbers
    int sum = K * (K + 1);
 
    // If sum is less then equal to N
    if (sum <= N) {
        System.out.println("YES");
    }
 
    // Otherwise
    else {
        System.out.println("No");
    }
}
 
// Driver Code
public static void main(String args[])
{
    int N = 16;
    int K = 3;
    isPossibleN(N, K);
}
}
 
// This code is contributed by jana_sayantan.


Python3
# Python3 program for the above approach
 
# Function to find if the sum
# of K even integers equals N
def isPossibleN(N, K) :
  
    # If N is odd, then its impossible
    # to obtain N from K even numbers
    if (N % 2 == 1) :
        print("NO")
        return
     
  
    # Sum first k even numbers
    sum = K * (K + 1)
  
    # If sum is less then equal to N
    if (sum <= N) :
        print("YES")
     
  
    # Otherwise
    else :
        print("NO")
  
    return
 
  
# Driver Code
 
N = 16
K = 3
  
isPossibleN(N, K)


C#
// C# implementation of the
// above approach
using System;
class GFG
{
 
  static void isPossibleN(int N, int K)
  {
 
    // If N is odd, then its impossible
    // to obtain N from K even numbers
    if (N % 2 == 1) {
      Console.WriteLine("NO");
      return;
    }
 
    // Sum first k even numbers
    int sum = K * (K + 1);
 
    // If sum is less then equal to N
    if (sum <= N) {
      Console.WriteLine("YES");
    }
 
    // Otherwise
    else {
      Console.WriteLine("No");
    }
  }
 
  // Driver Code
  public static void Main()
  {
    int N = 16;
    int K = 3;
    isPossibleN(N, K);
  }
}
 
// This code is contributed by jana_sayantan.


输出:
YES

时间复杂度: O(1)
辅助空间: O(1)