Find two proper factors of N such that their sum is coprime with N
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.
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
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:
Time Complexity: O(√N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.