📌  相关文章
📜  将N表示为K个奇数之和,且允许重复

📅  最后修改于: 2021-06-25 18:29:27             🧑  作者: Mango

给定两个整数NK ,任务是将N表示为K个奇数之和。如果无法创建总和,则输出-1
注意:表示形式可能包含重复的奇数。
例子:

方法:
为了解决上述问题,一个简单的解决方案是使1的出现最大化,这是可能的最小奇数。将数字N表示为K个奇数的必要条件是:

  • (K – 1)必须小于N。
  • N –(K – 1)必须是一个奇数。

下面是上述方法的实现:

C++
// C++ implementation to represent
// N as sum of K even numbers
  
#include 
  
using namespace std;
  
// Function to print the representation
void sumOddNumbers(int N, int K)
{
    int check = N - (K - 1);
  
    // N must be greater than equal to 2*K
    // and must be odd
    if (check > 0 && check % 2 == 1) {
        for (int i = 0; i < K - 1; i++) {
            cout << "1 ";
        }
        cout << check;
    }
    else
        cout << "-1";
}
  
// Driver Code
int main()
{
  
    int N = 5;
    int K = 3;
  
    sumOddNumbers(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 sumOddNumbers(int N, int K)
{
    int check = N - (K - 1);
  
    // N must be greater than equal 
    // to 2*K and must be odd
    if (check > 0 && check % 2 == 1)
    {
        for(int i = 0; i < K - 1; i++)
        {
           System.out.print("1 ");
        }
        System.out.print(+check);
    }
    else
        System.out.println("-1 ");
}
  
// Driver Code
public static void main(String args[])
{
    int N = 5;
    int K = 3;
  
    sumOddNumbers(N, K);
}
}
  
// This code is contributed by AbhiThakur


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


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


JavaScript


输出:
1 1 3

时间复杂度: O(K)