Represent N as sum of K odd numbers with repetitions allowed
Last Updated :
18 Sep, 2022
Given two integers N and K, the task is to represent N as sum of K odd numbers. If it is not possible to create the sum then output -1.
Note: The representation may contain duplicate odd numbers.
Examples:
Input: N = 5, K = 3
Output: 1, 1, 3
Explanation:
The given number N can be represented as 1 + 1 + 3 = 5
Input: N = 7, K = 5
Output: 1, 1, 1, 1, 3
Explanation:
The given number N can be represented as 1 + 1 + 1 + 1 + 3 = 7
Approach:
To solve the problem mentioned above a simple solution is to maximise the occurrence of 1 which is the possible smallest odd number. Necessary conditions for representing the number N as K odd numbers are:
- (K – 1) must be less than N.
- N – (K – 1) must be a Odd number.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void sumOddNumbers( int N, int K)
{
int check = N - (K - 1);
if (check > 0 && check % 2 == 1) {
for ( int i = 0; i < K - 1; i++) {
cout << "1 " ;
}
cout << check;
}
else
cout << "-1" ;
}
int main()
{
int N = 5;
int K = 3;
sumOddNumbers(N, K);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void sumOddNumbers( int N, int K)
{
int check = N - (K - 1 );
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 " );
}
public static void main(String args[])
{
int N = 5 ;
int K = 3 ;
sumOddNumbers(N, K);
}
}
|
Python3
def sumOddNumbers(N, K):
check = N - (K - 1 )
if (check > 0 and check % 2 = = 1 ):
for i in range ( 0 , K - 1 ):
print ( "1" , end = " " )
print (check, end = " " )
else :
print ( "-1" )
N = 5
K = 3 ;
sumOddNumbers(N, K)
|
C#
using System;
class GFG{
static void sumOddNumbers( int N, int K)
{
int check = N - (K - 1);
if (check > 0 && check % 2 == 1)
{
for ( int i = 0; i < K - 1; i++)
{
Console.Write( "1 " );
}
Console.Write(+check);
}
else
Console.WriteLine( "-1 " );
}
public static void Main()
{
int N = 5;
int K = 3;
sumOddNumbers(N, K);
}
}
|
JavaScript
<script>
function sumOddNumbers(N, K)
{
var check = N - (K - 1);
var i;
if (check > 0 && check % 2 == 1) {
for (i = 0; i < K - 1; i++) {
document.write( "1," + " " );
}
document.write(check + " " );
}
else
document.write( "-1" );
}
var N = 5;
var K = 3;
sumOddNumbers(N, K);
</script>
|
Time Complexity: O(k)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...