Coprime divisors of a number
Last Updated :
16 Oct, 2022
Given an integer N. The task is to find a pair of co-prime divisors of N, greater than 1. If such divisors don’t exists then print ‘-1’.
Examples:
Input: N = 45
Output: 3 5
Explanation: Since 3 and 5 are divisors of 45 and gcd( 3, 5 ) = 1 .
Hence, they satisfy the condition.
Input: N = 25
Output: -1
Explanation: No pair of divisors of 25 satisfy the condition such
that their gcd is 1.
Approach:
- Iterate from x = 2 to sqrt(N), to find all divisors of N
- For any value x, check if it divides N
- If it divides, then keep dividing N by x as long as it is divisible.
- Now, check if N > 1, then the pair of divisors (x, N) will have
gcd(x, N) == 1, since all the factors of ‘x’ has been eliminated from N.
- Similarly, check for all values of x.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findCoprimePair( int N)
{
for ( int x = 2; x <= sqrt (N); x++) {
if (N % x == 0) {
while (N % x == 0) {
N /= x;
}
if (N > 1) {
cout << x << " "
<< N << endl;
return ;
}
}
}
cout << -1 << endl;
}
int main()
{
int N = 45;
findCoprimePair(N);
N = 25;
findCoprimePair(N);
return 0;
}
|
Java
import java.util.*;
class GFG{
public static void findCoprimePair( int N)
{
for ( int x = 2 ; x <= Math.sqrt(N); x++)
{
if (N % x == 0 )
{
while (N % x == 0 )
{
N /= x;
}
if (N > 1 )
{
System.out.println(x + " " + N);
return ;
}
}
}
System.out.println(- 1 );
}
public static void main(String[] args)
{
int N = 45 ;
findCoprimePair(N);
N = 25 ;
findCoprimePair(N);
}
}
|
Python3
import math
def findCoprimePair(N):
for x in range ( 2 , int (math.sqrt(N)) + 1 ):
if (N % x = = 0 ):
while (N % x = = 0 ):
N / / = x
if (N > 1 ):
print (x, N)
return ;
print ( "-1" )
N = 45
findCoprimePair(N)
N = 25
findCoprimePair(N)
|
C#
using System;
class GFG{
public static void findCoprimePair( int N)
{
for ( int x = 2;
x <= Math.Sqrt(N); x++)
{
if (N % x == 0)
{
while (N % x == 0)
{
N /= x;
}
if (N > 1)
{
Console.WriteLine(x +
" " + N);
return ;
}
}
}
Console.WriteLine(-1);
}
public static void Main(String[] args)
{
int N = 45;
findCoprimePair(N);
N = 25;
findCoprimePair(N);
}
}
|
Javascript
<script>
function findCoprimePair(N)
{
for (let x = 2; x <= Math.sqrt(N); x++) {
if (N % x == 0) {
while (N % x == 0) {
N = Math.floor(N / x);
}
if (N > 1) {
document.write(x + " "
+ N + "<br>" );
return ;
}
}
}
document.write(-1 + "<br>" );
}
let N = 45;
findCoprimePair(N);
N = 25;
findCoprimePair(N);
</script>
|
Time Complexity: O(sqrt(N))
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...