Group all co-prime numbers from 1 to N
Last Updated :
08 Nov, 2021
Given an integer N, the task is to group numbers such that each group is mutually co-prime together with the total grouping is minimum.
Examples:
Input: N = 8
Output:
1 2 3
4 5
6 7
8
Input: N = 5
Output:
1 2 3
4 5
Approach: The key observation in this problem is two consecutive numbers are always co-prime. That is GCD(a, a+1) = 1. Another important observation is even numbers can’t be listed in one group. Because they will lead to the greatest common divisor of 2. Therefore, every consecutive even and odd numbers can be grouped into one group and 1 can be in any group because the greatest common divisor of numbers with 1 is always 1.
Below is the implementation of the above approach :
C++
#include<bits/stdc++.h>
using namespace std;
void mutually_coprime( int n)
{
if (n <= 3)
{
for ( int j = 1; j <= n; j++)
{
cout << j << " " ;
}
cout << "\n" ;
}
else
{
cout << "1 2 3\n" ;
for ( int j = 4; j < n; j += 2)
{
cout << j << " " << j + 1 << "\n" ;
}
if (n % 2 == 0)
cout << n << "\n" ;
}
}
int main()
{
int n = 9;
mutually_coprime(n);
}
|
Java
class GFG{
static void mutually_coprime( int n)
{
if (n <= 3 )
{
for ( int j = 1 ; j < n + 1 ; j++)
System.out.print(j + " " );
System.out.println();
}
else
{
System.out.println( "1 2 3" );
for ( int j = 4 ; j < n; j += 2 )
{
System.out.println(j + " " + (j + 1 ));
if (n % 2 == 0 )
System.out.println(n);
}
}
}
public static void main(String[] args)
{
int n = 9 ;
mutually_coprime(n);
}
}
|
Python3
def mutually_coprime (n):
if ( n < = 3 ):
for j in range ( 1 , n + 1 ):
print (j, end = " " )
print ()
else :
print ( 1 , 2 , 3 )
for j in range ( 4 , n, 2 ):
print (j, ( j + 1 ))
if (n % 2 = = 0 ):
print (n)
if __name__ = = "__main__" :
n = 9
mutually_coprime (n)
|
C#
using System;
class GFG{
static void mutually_coprime( int n)
{
if (n <= 3)
{
for ( int j = 1; j < n + 1; j++)
Console.Write(j + " " );
Console.WriteLine();
}
else
{
Console.WriteLine( "1 2 3" );
for ( int j = 4; j < n; j += 2)
{
Console.WriteLine(j + " " + (j + 1));
if (n % 2 == 0)
Console.WriteLine(n);
}
}
}
public static void Main(String[] args)
{
int n = 9;
mutually_coprime(n);
}
}
|
Javascript
<script>
function mutually_coprime(n)
{
if (n <= 3)
{
for (let j = 1; j < n + 1; j++)
document.write(j + " " + "<br/>" );
document.write( "<br/>" );
}
else
{
document.write( "1 2 3" + "<br/>" );
for (let j = 4; j < n; j += 2)
{
document.write(j + " " + (j + 1) + "<br/>" );
if (n % 2 == 0)
document.write(n + "<br/>" );
}
}
}
let n = 9;
mutually_coprime(n);
</script>
|
Output:
1 2 3
4 5
6 7
8 9
Time Complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...