Split first N natural numbers into two subsequences with non-coprime sums
Given an integer N (N &e; 3), the task is to split all numbers from 1 to N into two subsequences such that the sum of two subsequences is non-coprime to each other.
Examples:
Input: N = 5
Output:
{1, 3, 5}
{2, 4}
Explanation: Sum of the subsequence X[] = 1 + 3 + 5 = 9.
Sum of the subsequence Y[] = 2 + 4 = 6.
Since GCD(9, 6) is 3, the sums are not co-prime to each other.
Input: N = 4
Output:
{1, 4}
{2, 3}
Naive Approach: The simplest approach is to split first N natural numbers into two subsequences in all possible ways and for each combination, check if the sum of both the subsequences is non-coprime or not. IF found to be true for any pair of subsequences, print that subsequence and break out of loop.
Time Complexity: O(2N)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following observations:
From the above observation insert all the numbers from the range [1, N] in the one subsequence and N into another subsequence.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void printSubsequence( int N)
{
cout << "{ " ;
for ( int i = 1; i < N - 1; i++)
cout << i << ", " ;
cout << N - 1 << " }\n" ;
cout << "{ " << N << " }" ;
}
int main()
{
int N = 8;
printSubsequence(N);
return 0;
}
|
C
#include <stdio.h>
void printSubsequence( int N)
{
printf ( "{ " );
for ( int i = 1; i < N - 1; i++)
printf ( "%d " , i);
printf ( "%d}\n" , N - 1);
printf ( "{%d}" ,N);
}
int main()
{
int N = 8;
printSubsequence(N);
return 0;
}
|
Java
import java.io.*;
public class GFG
{
public static void printSubsequence( int N)
{
System.out.print( "{ " );
for ( int i = 1 ; i < N - 1 ; i++)
{
System.out.print(i + ", " );
}
System.out.println(N - 1 + " }" );
System.out.print( "{ " + N + " }" );
}
public static void main(String[] args)
{
int N = 8 ;
printSubsequence(N);
}
}
|
Python3
def printSubsequence(N):
print ( "{ " , end = "")
for i in range ( 1 , N - 1 ):
print (i, end = ", " )
print (N - 1 , end = " }\n" )
print ( "{" , N, "}" )
if __name__ = = '__main__' :
N = 8
printSubsequence(N)
|
C#
using System;
class GFG
{
public static void printSubsequence( int N)
{
Console.Write( "{ " );
for ( int i = 1; i < N - 1; i++)
{
Console.Write(i + ", " );
}
Console.WriteLine(N - 1 + " }" );
Console.Write( "{ " + N + " }" );
}
public static void Main( string [] args)
{
int N = 8;
printSubsequence(N);
}
}
|
Javascript
<script>
function printSubsequence(N)
{
document.write( "{ " );
for (let i = 1; i < N - 1; i++)
{
document.write(i + ", " );
}
document.write(N - 1 + " }" + "</br>" );
document.write( "{ " + N + " }" + "</br>" );
}
let N = 8;
printSubsequence(N);
</script>
|
Output:
{ 1, 2, 3, 4, 5, 6, 7 }
{ 8 }
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
09 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...