📌  相关文章
📜  将N表示为K个偶数之和

📅  最后修改于: 2021-06-26 11:38:45             🧑  作者: Mango

给定两个整数NK ,任务是将N表示为K个偶数之和。如果无法表示数字,请打印-1。
注意:表示形式可能包含重复的偶数。

例子:

方法:解决上述问题的一种简单方法是最大程度地减少2的出现,这是最小的偶数。将N表示为K个数之和的必要条件是:

  • (K – 1)* 2必须小于N。
  • N –(K – 1)* 2必须为偶数。

下面是上述方法的实现:

C++
// C++ implementation to represent
// N as sum of K even numbers
 
#include 
using namespace std;
 
// Function to print the representation
void sumEvenNumbers(int N, int K)
{
    int check = N - 2 * (K - 1);
 
    // N must be greater than equal to 2*K
    // and must be even
    if (check > 0 && check % 2 == 0) {
        for (int i = 0; i < K - 1; i++) {
            cout << "2 ";
        }
        cout << check;
    }
    else {
        cout << "-1";
    }
}
 
// Driver Code
int main()
{
    int N = 8;
    int K = 2;
 
    sumEvenNumbers(N, K);
    return 0;
}


Java
// Java implementation to represent
// N as sum of K even numbers
import java.util.*;
 
class GFG{
     
// Function to print the representation
static void sumEvenNumbers(int N, int K)
{
    int check = N - 2 * (K - 1);
 
    // N must be greater than equal to 2 * K
    // and must be even
    if (check > 0 && check % 2 == 0)
    {
        for(int i = 0; i < K - 1; i++)
        {
           System.out.print("2 ");
        }
        System.out.println(check);
    }
    else
    {
        System.out.println("-1");
    }
}
 
// Driver Code
public static void main(String args[])
{
    int N = 8;
    int K = 2;
 
    sumEvenNumbers(N, K);
}
}
 
// This code is contributed by ANKITKUMAR34


Python3
# Python3 implementation to represent
# N as sum of K even numbers
 
# Function to print the representation
def sumEvenNumbers(N, K):
     
    check = N - 2 * (K - 1)
 
    # N must be greater than equal to 2 * K
    # and must be even
    if (check > 0 and check % 2 == 0):
        for i in range(K - 1):
            print("2 ", end = "")
             
        print(check)
    else:
        print("-1")
 
# Driver Code
N = 8
K = 2
sumEvenNumbers(N, K)
 
# This code is contributed by ANKITKUMAR34


C#
// C# implementation to represent
// N as sum of K even numbers
using System;
 
class GFG{
     
// Function to print the representation
static void sumEvenNumbers(int N, int K)
{
    int check = N - 2 * (K - 1);
 
    // N must be greater than equal to
    //  2 * K and must be even
    if (check > 0 && check % 2 == 0)
    {
        for(int i = 0; i < K - 1; i++)
        {
           Console.Write("2 ");
        }
        Console.WriteLine(check);
    }
    else
    {
        Console.WriteLine("-1");
    }
}
 
// Driver Code
static public void Main(String []args)
{
    int N = 8;
    int K = 2;
 
    sumEvenNumbers(N, K);
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
2 6

时间复杂度: O(K)