Find two proper factors of N such that their sum is coprime with N
Last Updated :
16 Aug, 2021
Given an integer N, you have to find two proper factors of N such that their sum is coprime with the given integer N. If no such factors exist, print -1.
Examples:
Input: N = 15
Output: 3, 5
Explanation: 3 and 5 are the proper factors of 15 and 3+5 -> 8 is coprime with 15.
Input: N = 4
Output: -1
Explanation: there are no proper factors that satisfy the required conditions
Naive Approach: Generate a list of all the proper factors of N and for each possible pair, check if their sum is coprime with N i.e. GCD(sum of pair of integers, N) = 1. Here GCD means Greatest Common Divisor.
Efficient Approach: If two numbers A and B are coprime then their sum is coprime with their product. Keeping that in mind, find all the factors of N and for each factor d1, calculate the largest factor of N, d2 that is coprime with d1. To calculate d2, simply divide N with d1 until N%d1 != 0. Finally, check if d1 and d2 are proper factors of N or not (i.e., d1>1 and d2>1).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printFactors( int n)
{
for ( int i = 2; i <= sqrt (n); i++) {
if (n % i == 0) {
int d1 = i, d2 = n;
while (d2 % d1 == 0) {
d2 = d2 / d1;
}
if (d1 > 1 && d2 > 1) {
cout << d1 << ", " << d2;
return ;
}
}
}
cout << -1;
}
int main()
{
int N = 10;
printFactors(N);
return 0;
}
|
Java
import java.io.*;
class GFG{
static void printFactors( int n)
{
for ( int i = 2 ; i <= ( int )Math.sqrt(n); i++)
{
if (n % i == 0 )
{
int d1 = i, d2 = n;
while (d2 % d1 == 0 )
{
d2 = d2 / d1;
}
if (d1 > 1 && d2 > 1 )
{
System.out.print(d1 + ", " + d2);
return ;
}
}
}
System.out.print(- 1 );
}
public static void main(String[] args)
{
int N = 10 ;
printFactors(N);
}
}
|
Python3
import math
def printFactors(n):
for i in range ( 2 , int (math.sqrt(n)) + 1 ):
if (n % i = = 0 ):
d1 = i
d2 = n
while (d2 % d1 = = 0 ):
d2 = d2 / / d1
if (d1 > 1 and d2 > 1 ):
print (d1, d2, sep = ", " )
return
print ( - 1 )
N = 10
printFactors(N)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void printFactors( int n)
{
for ( int i = 2; i <= ( int )Math.Sqrt(n); i++) {
if (n % i == 0) {
int d1 = i, d2 = n;
while (d2 % d1 == 0) {
d2 = d2 / d1;
}
if (d1 > 1 && d2 > 1)
{
Console.Write(d1 + ", " +d2);
return ;
}
}
}
Console.Write(-1);
}
public static void Main()
{
int N = 10;
printFactors(N);
}
}
|
Javascript
<script>
function printFactors(n) {
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
let d1 = i,
d2 = n;
while (d2 % d1 == 0) {
d2 = Math.floor(d2 / d1);
}
if (d1 > 1 && d2 > 1) {
document.write(d1 + ", " + d2);
return ;
}
}
}
document.write(-1);
}
let N = 10;
printFactors(N);
</script>
|
Time Complexity: O(?N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...