Given two integers N and K, the task is to find K distinct positive odd integers such that their sum is equal to the given number N.
Examples:
Input: N = 10, K = 2
Output: 1 9
Explanation:
Two odd positive integers such that their sum is 10 can be (1, 9) or (3, 7).
Input: N = 10, K = 4
Output: NO
Explanation:
There does not exists four odd positive integers with sum 10.
Approach:
The number N can be represented as the sum of K positive odd integers only is the following two conditions satisfies:
- If the square of K is less than or equal to N and,
- If the sum of N and K is an even number.
If these conditions are satisfied then there exist K positive odd integers whose sum is N.
To generate K such odd numbers:
- Print first K-1 odd numbers starting from 1, i.e. 1, 3, 5, 7, 9…….
- The last odd number will be : N – (Sum of first K-1 odd positive integers)
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
void findDistinctOddSum(ll n, ll k)
{
if ((k * k) <= n &&
(n + k) % 2 == 0){
int val = 1;
int sum = 0;
for ( int i = 1; i < k; i++){
cout << val << " " ;
sum += val;
val += 2;
}
cout << n - sum << endl;
}
else
cout << "NO \n" ;
}
int main()
{
ll n = 100;
ll k = 4;
findDistinctOddSum(n, k);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void findDistinctOddSum( int n, int k)
{
if ((k * k) <= n &&
(n + k) % 2 == 0 ){
int val = 1 ;
int sum = 0 ;
for ( int i = 1 ; i < k; i++){
System.out.print(val+ " " );
sum += val;
val += 2 ;
}
System.out.print(n - sum + "\n" );
}
else
System.out.print( "NO \n" );
}
public static void main(String[] args)
{
int n = 100 ;
int k = 4 ;
findDistinctOddSum(n, k);
}
}
|
Python3
def findDistinctOddsumm(n, k):
if ((k * k) < = n and (n + k) % 2 = = 0 ):
val = 1
summ = 0
for i in range ( 1 , k):
print (val, end = " " )
summ + = val
val + = 2
print (n - summ)
else :
print ( "NO" )
n = 100
k = 4
findDistinctOddsumm(n, k)
|
C#
using System;
public class GFG{
static void findDistinctOddSum( int n, int k)
{
if ((k * k) <= n &&
(n + k) % 2 == 0){
int val = 1;
int sum = 0;
for ( int i = 1; i < k; i++){
Console.Write(val+ " " );
sum += val;
val += 2;
}
Console.Write(n - sum + "\n" );
}
else
Console.Write( "NO \n" );
}
public static void Main(String[] args)
{
int n = 100;
int k = 4;
findDistinctOddSum(n, k);
}
}
|
Javascript
<script>
function findDistinctOddSum(n,k)
{
if ((k * k) <= n &&
(n + k) % 2 == 0){
var val = 1;
var sum = 0;
for ( var i = 1; i < k; i++){
document.write( val+ " " );
sum += val;
val += 2;
}
document.write( n - sum) ; }
else
document.write( "NO \n" );
}
var n = 100;
var k = 4;
findDistinctOddSum(n, k);
</script>
|
Performance Analysis:
- Time Complexity: In the above-given approach, there is one loop which takes O(K) time in the worst case. Therefore, the time complexity for this approach will be O(K).
- Auxiliary Space: O(1)