Partition first N natural number into two sets such that their sum is not coprime
Last Updated :
30 Aug, 2022
Given an integer N, the task is to partition the first N natural numbers in two non-empty sets such that the sum of these sets is not coprime to each other. If it is possible then find the possible partition then print -1 else print the sum of elements of both sets.
Examples:
Input: N = 5
Output: 10 5
{1, 2, 3, 4} and {5} are the valid partitions.
Input: N = 2
Output: -1
Approach:
- If N ? 2 then print -1 as the only possible partition is {1} and {2} where the sum of both sets are coprime to each other.
- Now if N is odd then we put N in one set and first (N – 1) numbers into other sets. So the sum of the two sets will be N and N * (N – 1) / 2 and as their gcd is N, they will not be coprime to each other.
- If N is even then we do the same thing as previous and sum of the two sets will be N and N * (N – 1) / 2. As N is even, (N – 1) is not divisible by 2 but N is divisible which gives sum as (N / 2) * (N – 1) and their gcd will be N / 2. Since N / 2 is a factor of N, so they are no coprime to each other.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void find_set( int n)
{
if (n <= 2) {
cout << "-1" ;
return ;
}
int sum1 = (n * (n - 1)) / 2;
int sum2 = n;
cout << sum1 << " " << sum2;
}
int main()
{
int n = 8;
find_set(n);
return 0;
}
|
C
#include <stdio.h>
void find_set( int n)
{
if (n <= 2) {
printf ( "-1" );
return ;
}
int sum1 = (n * (n - 1)) / 2;
int sum2 = n;
printf ( "%d %d" , sum1, sum2);
}
int main()
{
int n = 8;
find_set(n);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static void find_set( int n)
{
if (n <= 2 )
{
System.out.println ( "-1" );
return ;
}
int sum1 = (n * (n - 1 )) / 2 ;
int sum2 = n;
System.out.println (sum1 + " " +sum2 );
}
public static void main (String[] args)
{
int n = 8 ;
find_set(n);
}
}
|
Python3
def find_set(n):
if (n < = 2 ):
print ( "-1" );
return ;
sum1 = (n * (n - 1 )) / 2 ;
sum2 = n;
print (sum1, " " , sum2);
n = 8 ;
find_set(n);
|
C#
using System;
class GFG
{
static void find_set( int n)
{
if (n <= 2)
{
Console.WriteLine( "-1" );
return ;
}
int sum1 = (n * (n - 1)) / 2;
int sum2 = n;
Console.WriteLine(sum1 + " " +sum2 );
}
public static void Main ()
{
int n = 8;
find_set(n);
}
}
|
Javascript
<script>
function find_set(n)
{
if (n <= 2)
{
document.write( "-1" );
return ;
}
let sum1 = parseInt((n * (n - 1)) / 2, 10);
let sum2 = n;
document.write(sum1 + " " +sum2 + "</br>" );
}
let n = 8;
find_set(n);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1) because it is using constant variables
Share your thoughts in the comments
Please Login to comment...