Given an integer X, the task is to find two integers A and B such that LCM(A, B) = X and the difference between the A and B is minimum possible.
Examples:
Input: X = 6
Output: 2 3
LCM(2, 3) = 6 and (3 – 2) = 1
which is the minimum possible.
Input X = 7
Output: 1 7
Approach: An approach to solve this problem is to find all the factors of the given number using the approach discussed in this article and then find the pair (A, B) that satisfies the given conditions and has the minimum possible difference.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int lcm( int a, int b)
{
return (a / __gcd(a, b) * b);
}
void findNums( int x)
{
int ans;
for ( int i = 1; i <= sqrt (x); i++) {
if (x % i == 0 && lcm(i, x / i) == x) {
ans = i;
}
}
cout << ans << " " << (x / ans);
}
int main()
{
int x = 12;
findNums(x);
return 0;
}
|
Java
class GFG
{
static int lcm( int a, int b)
{
return (a / __gcd(a, b) * b);
}
static int __gcd( int a, int b)
{
return b == 0 ? a : __gcd(b, a % b);
}
static void findNums( int x)
{
int ans = - 1 ;
for ( int i = 1 ; i <= Math.sqrt(x); i++)
{
if (x % i == 0 && lcm(i, x / i) == x)
{
ans = i;
}
}
System.out.print(ans + " " + (x / ans));
}
public static void main(String[] args)
{
int x = 12 ;
findNums(x);
}
}
|
Python3
from math import gcd as __gcd, sqrt, ceil
def lcm(a, b):
return (a / / __gcd(a, b) * b)
def findNums(x):
ans = 0
for i in range ( 1 , ceil(sqrt(x))):
if (x % i = = 0 and lcm(i, x / / i) = = x):
ans = i
print (ans, (x / / ans))
x = 12
findNums(x)
|
C#
using System;
class GFG
{
static int lcm( int a, int b)
{
return (a / __gcd(a, b) * b);
}
static int __gcd( int a, int b)
{
return b == 0 ? a : __gcd(b, a % b);
}
static void findNums( int x)
{
int ans = -1;
for ( int i = 1; i <= Math.Sqrt(x); i++)
{
if (x % i == 0 && lcm(i, x / i) == x)
{
ans = i;
}
}
Console.Write(ans + " " + (x / ans));
}
public static void Main(String[] args)
{
int x = 12;
findNums(x);
}
}
|
Javascript
<script>
function lcm(a,b)
{
return (a / __gcd(a, b) * b);
}
function __gcd(a,b)
{
return b == 0 ? a : __gcd(b, a % b);
}
function findNums(x)
{
let ans = -1;
for (let i = 1; i <= Math.sqrt(x); i++)
{
if (x % i == 0 && lcm(i, Math.floor(x / i)) == x)
{
ans = i;
}
}
document.write(ans + " " + Math.floor(x / ans));
}
let x = 12;
findNums(x);
</script>
|
Time Complexity: O(n1/2 * log(max(a, b)))
Auxiliary Space: O(log(max(a, b)))
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
20 Feb, 2022
Like Article
Save Article