Find N distinct integers with sum N
Last Updated :
22 Feb, 2023
Given an integer N, the task is to find N distinct integers whose sum is N. If there is more than one combination of the integers, print any one of them.
Examples:
Input: N = 3
Output: 1, -1, 3
Explanation:
On adding the numbers that is 1 + (-1) + 3 the sum is 3.
Input: N = 4
Output: 1, -1, 0, 4
Explanation:
On adding the numbers that is 1 + (-1) + 0 + (4) the sum is 4.
Approach: The idea is to print N/2 Symmetric Pairs like (+x, -x) so that the resultant sum will always be 0.
Now if integer N is odd, then print N along with these set of integers to make sum of all integers equals to N
If N is even, print 0 and N along with these set of integers to make sum of all integers equals to N.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findNumbers( int N)
{
int half = N / 2;
if (N % 2 == 0) {
half--;
}
for ( int i = 1; i <= half; i++) {
cout << (-1) * i
<< ", " << i << ", " ;
}
if (N & 1) {
cout << N << endl;
}
else {
cout << 0 << ", "
<< N << endl;
}
}
int main()
{
int N = 5;
findNumbers(N);
return 0;
}
|
Java
class GFG{
public static void findNumbers( int N)
{
int half = N / 2 ;
if (N % 2 == 0 )
{
half--;
}
for ( int i = 1 ; i <= half; i++)
{
System.out.print((- 1 ) * i + ", " +
i + ", " );
}
int check = N & 1 ;
if (check != 0 )
{
System.out.println(N);
}
else
{
System.out.println( 0 + ", " + N);
}
}
public static void main(String[] args)
{
int N = 5 ;
findNumbers(N);
}
}
|
Python3
def findNumbers(N):
half = int (N / 2 )
if (N % 2 = = 0 ):
half = half - 1
for i in range ( 1 , half + 1 ):
print (( - 1 ) * i, end = ', ' )
print (i, end = ', ' )
if (N & 1 ):
print (N, end = '\n' )
else :
print ( 0 , end = ', ' )
print (N, end = '\n' )
N = 5
findNumbers(N)
|
C#
using System;
class GFG{
public static void findNumbers( int N)
{
int half = N / 2;
if (N % 2 == 0)
{
half--;
}
for ( int i = 1; i <= half; i++)
{
Console.Write((-1) * i + ", " +
i + ", " );
}
int check = N & 1;
if (check != 0)
{
Console.Write(N + "\n" );
}
else
{
Console.Write(0 + ", " + N + "\n" );
}
}
public static void Main( string [] args)
{
int N = 5;
findNumbers(N);
}
}
|
Javascript
<script>
function findNumbers( N)
{
let half = parseInt(N / 2);
if (N % 2 == 0) {
half--;
}
for (let i = 1; i <= half; i++) {
document.write( (-1) * i
+ ", " + i + ", " );
}
if (N & 1) {
document.write( N);
}
else {
document.write( 0 + ", "
+ N + "<br/>" );
}
}
let N = 5;
findNumbers(N);
</script>
|
Output:
-1,1,-2,2,5
Time Complexity: O(N/2) which is asymptotically same as O(N).
Space Complexity: O(1) as no extra space has been used.
Share your thoughts in the comments
Please Login to comment...