VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-number-to-be-added-to-minimize-lcm-of-two-given-numbers/

⇱ Minimum number to be added to minimize LCM of two given numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum number to be added to minimize LCM of two given numbers

Last Updated : 23 Jul, 2025

Given two numbers A and B, the task is to find the minimum number that needs to be added to A and B such that their LCM is minimized.

Examples:

Input: A = 6, B = 10
Output: 2
Explanation: On adding 2 to A and B, the value becomes 8 and 12 respectively. LCM of 8 and 12 is 24, which is the minimum LCM possible.

Input: A = 5, B = 10
Output: 0
Explanation:
10 is already the minimum LCM of both the given number.
Hence, the minimum number added is 0.

Approach: The idea is based on the generalized formula that the LCM of (A + x) and (B + x) is equal to (A + x)*(B + x) / GCD(A + x, B + x). It can be observed that GCD of (A + x) and (B + x) is is equal to the GCD of (B - A) and (A + x). So, the gcd is a divisor of (B ? A).

Therefore, iterate over all the divisors of (B ? A) and if A % M = B % M (if M is one of the divisors), then the value of X(the minimum value must be added) is equal to M ? A % M.

Below is the implementation of the above approach:


Output: 
2

 

Time Complexity: O(sqrt(B - A))
Auxiliary Space: O(max(A, B))

Comment