Find N distinct integers with zero sum
Last Updated :
28 May, 2022
Given an integer N, our task is to print N distinct numbers such that their sum is 0.
Examples:
Input: N = 3
Output: 1, -1, 0
Explanation:
On adding the numbers that is 1 + (-1) + 0 the sum is 0.
Input: N = 4
Output: 1, -1, 2, -2
Explanation:
On adding the numbers that is 1 + (-1) + 2 + (-2) the sum is 0.
Approach: To solve the problem mentioned above the main idea is to print Symmetric Pairs like (+x, -x) so that the sum will always be 0. The edge case to the problem is to observe that if integer N is odd, then print one 0 along with the numbers so that sum is not affected.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findNumbers( int N)
{
for ( int i = 1; i <= N / 2; i++) {
cout << i << ", " << -i << ", " ;
}
if (N % 2 == 1)
cout << 0;
}
int main()
{
int N = 10;
findNumbers(N);
}
|
Java
class GFG{
static void findNumbers( int N)
{
for ( int i = 1 ; i <= N / 2 ; i++)
{
System.out.print(i + ", " + -i + ", " );
}
if (N % 2 == 1 )
System.out.print( 0 );
}
public static void main(String[] args)
{
int N = 10 ;
findNumbers(N);
}
}
|
Python3
def findNumbers(N):
for i in range ( 1 , N / / 2 + 1 ):
print (i, end = ', ' )
print ( - i, end = ', ' )
if N % 2 = = 1 :
print ( 0 , end = '')
if __name__ = = '__main__' :
N = 10
findNumbers(N)
|
C#
using System;
class GFG {
static void findNumbers( int N)
{
for ( int i = 1; i <= (N / 2); i++)
{
Console.Write(i + ", " + -i + ", " );
}
if (N % 2 == 1)
Console.Write(0);
}
static void Main()
{
int N = 10;
findNumbers(N);
}
}
|
Javascript
<script>
function findNumbers(N)
{
for ( var i = 1; i <= N / 2; i++) {
document.write( i + ", " + -i + ", " );
}
if (N % 2 == 1)
document.write( 0);
}
var N = 10;
findNumbers(N);
</script>
|
Output:
1, -1, 2, -2, 3, -3, 4, -4, 5, -5,
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...