Given an integer X, We need to find two numbers a and b such that their LCM is equal to X and the maximum of the two is the lowest possible. *LCM stands for lowest common multiple.
Examples :
Input : 6
Output : 2 3
For X=6, all possible combinations of (a, b) such that LCM(a, b)=6 are
{(1, 6), (2, 3)}.
Among these pairs, max(2, 3)<max(1, 6).Thus, the required answer
is(2, 3)
Input : 16548
Output : 84 197
Approach :
The answer always exists and the only possible combinations are the co-prime divisors of the number such that their product is equal to the number itself.We need to store all possible co-prime divisors of X whose product equals X.Then we can iterate over them and check for which pair, the maximum of the numbers in the pair comes out to be the smallest.The pair whose maximum comes out to be the smallest of all is the answer.
Step 1: Store all possible combinations of a and b such that a and b are coprime and their LCM equals X.This can be easily done if we find co-prime divisors of X whose product equals X.
Step 2: Iterate over the list and find out the pair whose maximum is the smallest
Implementation :
#include <bits/stdc++.h>
using namespace std;
// Program to find the highest common factor of two numbers
int hcf(int a, int b)
{
if (b == 0)
return a;
return hcf(b, a % b);
}
void solve(int X)
{
int i, a = 0, b = 0, mn = 1e9;
vector<pair<int, int> > v;
for (i = 1; i * i <= X; i++) {
// Checking if i is a factor of X
if (X % i == 0) {
// Checking whether i and X/i are co-prime
if (hcf(i, X / i) == 1) {
v.push_back({ i, X / i });
}
}
}
for (i = 0; i < v.size(); i++) {
// Finding minimum of the maximum of the numbers in pairs
if (max(v[i].first, v[i].second) < mn) {
mn = max(v[i].first, v[i].second);
a = v[i].first;
b = v[i].second;
}
}
cout << a << " " << b;
}
// Driver code
int main()
{
int X;
X = 16548;
solve(X);
return 0;
}
import math
# Program to find the highest common factor of two numbers
def hcf(a, b):
if (b == 0):
return a
else:
return hcf(b, a % b)
def solve(X):
v =[]
mn = 1e9; a = 0; b = 0
for i in range(1, int(math.sqrt(X)) + 1):
# Checking if i is a factor of X
if (X % i == 0):
# Checking whether i and X / i are co-prime
if(hcf(i, X // i) == 1):
v.append([i, X // i])
for i in range(0, len(v)):
if(max(v[i][0], v[i][1]) < mn):
mn = max(v[i][0], v[i][1])
a = v[i][0]
b = v[i][1]
print(a, b)
# driver code
if __name__ == "__main__" :
X = 16548
solve(X)
Time Complexity : O(sqrt(n))