Given two integers N and K, the task is to represent N as the sum of K even number. If it is not possible to represent the number, print -1.
Note: The representation may contain duplicate even numbers.
Examples:
Input: N = 6, K = 3
Output: 2 2 2
Explanation:
The given number 6 can be represented as 2 + 2 + 2 = 6
Input: N = 8, K = 2
Output: 2 6
Explanation:
The given number 3 can be represented as 2 + 6 = 8
Approach: To solve the problem mentioned above a simple solution is to maximize the occurrence of 2 which is the smallest even number. The necessary condition to represent N as the sum of K numbers are:
- (K – 1) * 2 must be less than N.
- N – (K – 1) * 2 must be Even.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void sumEvenNumbers( int N, int K)
{
int check = N - 2 * (K - 1);
if (check > 0 && check % 2 == 0) {
for ( int i = 0; i < K - 1; i++) {
cout << "2 " ;
}
cout << check;
}
else {
cout << "-1" ;
}
}
int main()
{
int N = 8;
int K = 2;
sumEvenNumbers(N, K);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void sumEvenNumbers( int N, int K)
{
int check = N - 2 * (K - 1 );
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" );
}
}
public static void main(String args[])
{
int N = 8 ;
int K = 2 ;
sumEvenNumbers(N, K);
}
}
|
Python3
def sumEvenNumbers(N, K):
check = N - 2 * (K - 1 )
if (check > 0 and check % 2 = = 0 ):
for i in range (K - 1 ):
print ( "2 " , end = "")
print (check)
else :
print ( "-1" )
N = 8
K = 2
sumEvenNumbers(N, K)
|
C#
using System;
class GFG{
static void sumEvenNumbers( int N, int K)
{
int check = N - 2 * (K - 1);
if (check > 0 && check % 2 == 0)
{
for ( int i = 0; i < K - 1; i++)
{
Console.Write( "2 " );
}
Console.WriteLine(check);
}
else
{
Console.WriteLine( "-1" );
}
}
static public void Main(String []args)
{
int N = 8;
int K = 2;
sumEvenNumbers(N, K);
}
}
|
Javascript
<script>
function sumEvenNumbers(N, K)
{
let check = N - 2 * (K - 1);
if (check > 0 && check % 2 == 0)
{
for (let i = 0; i < K - 1; i++)
{
document.write( "2 " );
}
document.write(check);
}
else
{
document.write( "-1" );
}
}
let N = 8;
let K = 2;
sumEvenNumbers(N, K);
</script>
|
Time Complexity: O(K)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
02 Mar, 2022
Like Article
Save Article