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

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:
C++
// C++ program for the above approachÂ
#include "bits/stdc++.h"using namespace std;Â
// Function for finding all divisors// of a given numbervector<int> getDivisors(int diff){    // Stores the divisors of the    // number diff    vector<int> divisor;Â
    for (int i = 1; i * i <= diff; i++) {Â
        // If diff is a perfect square        if (i == diff / i) {            divisor.push_back(i);            continue;        }Â
        // If i divides diff then        // diff / i also a divisor        if (diff % i == 0) {            divisor.push_back(i);            divisor.push_back(diff / i);        }    }Â
    // Return the divisors stored    return divisor;}Â
// Function to find smallest integer x// such that LCM of (A + X) and (B + X)// is minimizedint findTheSmallestX(int a, int b){Â Â Â Â int diff = b - a;Â
    // Find all the divisors of diff    vector<int> divisor        = getDivisors(diff);Â
    // Find LCM of a and b    int lcm = (a * b) / __gcd(a, b);Â
    int ans = 0;Â
    for (int i = 0;         i < (int)divisor.size(); i++) {Â
        // From equation x = M - a % M        // here M = divisor[i]        int x = (divisor[i]                 - (a % divisor[i]));Â
        // If already checked for x == 0        if (!x)            continue;Â
        // Find the product        int product = (b + x) * (a + x);Â
        // Find the GCD        int tempGCD = __gcd(a + x, b + x);        int tempLCM = product / tempGCD;Â
        // If current lcm is minimum        // than previous lcm, update ans        if (lcm > tempLCM) {            ans = x;            lcm = tempLCM;        }    }Â
    // Print the number added    cout << ans;}Â
// Driver Codeint main(){Â Â Â Â // Given A & BÂ Â Â Â int A = 6, B = 10;Â
    // Function Call    findTheSmallestX(A, B);Â
    return 0;} |
Java
// Java program for the // above approachimport java.util.*;class GFG{   // Recursive function to // return gcd of a and b static int __gcd(int a, int b) {   return b == 0 ? a :          __gcd(b, a % b);    }   // Function for finding all // divisors of a given numberstatic int[] getDivisors(int diff){  // Stores the divisors of   // the number diff  Vector<Integer> divisor =          new Vector<>() ;Â
  for (int i = 1;            i * i <= diff; i++)   {    // If diff is a perfect    // square    if (i == diff / i)     {      divisor.add(i);      continue;    }Â
    // If i divides diff then    // diff / i also a divisor    if (diff % i == 0)     {      divisor.add(i);      divisor.add(diff / i);    }  }     int []ans = new int[divisor.size()];  int j = 0;     for(int i: divisor)    ans[j] = i;     // Return the divisors  // stored  return ans;}Â
// Function to find smallest integer // x such that LCM of (A + X) and // (B + X) is minimizedstatic void findTheSmallestX(int a, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int b){Â Â int diff = b - a;Â
  // Find all the divisors   // of diff  int[] divisor =         getDivisors(diff);Â
  // Find LCM of a and b  int lcm = (a * b) /              __gcd(a, b);Â
  int ans = 0;Â
  for (int i = 0;           i <divisor.length; i++)   {    // From equation x = M - a % M    // here M = divisor[i]    int x = 0;         if(divisor[i] != 0)      x = (divisor[i] -           (a % divisor[i]));Â
    // If already checked for    // x == 0    if (x == 0)      continue;Â
    // Find the product    int product = (b + x) *                   (a + x);Â
    // Find the GCD    int tempGCD = __gcd(a + x,                        b + x);    int tempLCM = product /                   tempGCD;Â
    // If current lcm is     // minimum than previous     // lcm, update ans    if (lcm > tempLCM)     {      ans = x;      lcm = tempLCM;    }  }Â
  // Print the number   // added  System.out.print(ans);}Â
// Driver Codepublic static void main(String[] args){Â Â // Given A & BÂ Â int A = 6, B = 10;Â
  // Function Call  findTheSmallestX(A, B);}}Â
// This code is contributed by 29AjayKumar |
Python3
# Python3 program for the above approachfrom math import gcdÂ
# Function for finding all divisors# of a given numberdef getDivisors(diff):         # Stores the divisors of the    # number diff    divisor = []Â
    for i in range(1, diff):        if i * i > diff:            breakÂ
        # If diff is a perfect square        if (i == diff // i):            divisor.append(i)            continueÂ
        # If i divides diff then        # diff / i also a divisor        if (diff % i == 0):            divisor.append(i)            divisor.append(diff // i)Â
    # Return the divisors stored    return divisorÂ
# Function to find smallest integer x# such that LCM of (A + X) and (B + X)# is minimizeddef findTheSmallestX(a, b):Â Â Â Â Â Â Â Â Â diff = b - aÂ
    # Find all the divisors of diff    divisor = getDivisors(diff)Â
    # Find LCM of a and b    lcm = (a * b) // gcd(a, b)Â
    ans = 0Â
    for i in range(len(divisor)):Â
        # From equation x = M - a % M        # here M = divisor[i]        x = (divisor[i] - (a % divisor[i]))Â
        # If already checked for x == 0        if (not x):            continueÂ
        # Find the product        product = (b + x) * (a + x)Â
        # Find the GCD        tempGCD = gcd(a + x, b + x)        tempLCM = product // tempGCDÂ
        # If current lcm is minimum        # than previous lcm, update ans        if (lcm > tempLCM):            ans = x            lcm = tempLCMÂ
    # Print the number added    print(ans)Â
# Driver Codeif __name__ == '__main__':Â Â Â Â Â Â Â Â Â # Given A & BÂ Â Â Â A = 6Â Â Â Â B = 10Â
    # Function Call    findTheSmallestX(A, B)Â
# This code is contributed by mohit kumar 29 |
C#
// C# program for the // above approachusing System;using System.Collections.Generic;Â
class GFG{   // Recursive function to // return gcd of a and b static int __gcd(int a, int b) {   return b == 0 ? a :          __gcd(b, a % b);    }   // Function for finding all // divisors of a given numberstatic int[] getDivisors(int diff){     // Stores the divisors of   // the number diff  List<int> divisor = new List<int>();Â
  for(int i = 1; i * i <= diff; i++)   {         // If diff is a perfect    // square    if (i == diff / i)     {      divisor.Add(i);      continue;    }Â
    // If i divides diff then    // diff / i also a divisor    if (diff % i == 0)     {      divisor.Add(i);      divisor.Add(diff / i);    }  }     int []ans = new int[divisor.Count];  int j = 0;     foreach(int i in divisor)    ans[j] = i;     // Return the divisors  // stored  return ans;}Â
// Function to find smallest integer // x such that LCM of (A + X) and // (B + X) is minimizedstatic void findTheSmallestX(int a, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int b){Â Â int diff = b - a;Â
  // Find all the divisors   // of diff  int[] divisor = getDivisors(diff);Â
  // Find LCM of a and b  int lcm = (a * b) / __gcd(a, b);Â
  int ans = 0;Â
  for(int i = 0;          i < divisor.Length; i++)   {         // From equation x = M - a % M    // here M = divisor[i]    int x = 0;         if (divisor[i] != 0)      x = (divisor[i] -       (a % divisor[i]));Â
    // If already checked for    // x == 0    if (x == 0)      continue;Â
    // Find the product    int product = (b + x) *                   (a + x);Â
    // Find the GCD    int tempGCD = __gcd(a + x,                        b + x);    int tempLCM = product /                   tempGCD;Â
    // If current lcm is     // minimum than previous     // lcm, update ans    if (lcm > tempLCM)     {      ans = x;      lcm = tempLCM;    }  }     // Print the number   // added  Console.Write(ans);}Â
// Driver Codepublic static void Main(String[] args){Â Â Â Â Â // Given A & BÂ Â int A = 6, B = 10;Â
  // Function Call  findTheSmallestX(A, B);}}Â
// This code is contributed by 29AjayKumar |
Javascript
<script>Â
// JavaScript program for the// above approachÂ
// Recursive function to// return gcd of a and b function __gcd(a,b){Â Â Â Â return b == 0 ? a :Â Â Â Â Â Â Â Â Â __gcd(b, a % b);Â Â Â }Â
// Function for finding all// divisors of a given numberfunction getDivisors(diff){     // Stores the divisors of  // the number diff  let divisor = [];              for (let i = 1;           i * i <= diff; i++)  {    // If diff is a perfect    // square    if (i == diff / i)    {      divisor.push(i);      continue;    }      // If i divides diff then    // diff / i also a divisor    if (diff % i == 0)    {      divisor.push(i);      divisor.push(diff / i);    }  }      let ans = new Array(divisor.length);  let j = 0;      for(let i=0;i< divisor.length;i++)    ans[i] = divisor[i];      // Return the divisors  // stored  return ans;}Â
// Function to find smallest integer// x such that LCM of (A + X) and// (B + X) is minimizedfunction findTheSmallestX(a,b){    let diff = b - a;    // Find all the divisors  // of diff  let divisor =        getDivisors(diff);    // Find LCM of a and b  let lcm = (a * b) /             __gcd(a, b);    let ans = 0;    for (let i = 0;           i <divisor.length; i++)  {    // From equation x = M - a % M    // here M = divisor[i]    let x = 0;          if(divisor[i] != 0)      x = (divisor[i] -          (a % divisor[i]));      // If already checked for    // x == 0    if (x == 0)      continue;      // Find the product    let product = (b + x) *                  (a + x);      // Find the GCD    let tempGCD = __gcd(a + x,                        b + x);    let tempLCM = product /                  tempGCD;      // If current lcm is    // minimum than previous    // lcm, update ans    if (lcm > tempLCM)    {      ans = x;      lcm = tempLCM;    }  }    // Print the number  // added  document.write(ans);}Â
// Driver CodeÂ
// Given A & Blet A = 6, B = 10;Â
// Function CallfindTheSmallestX(A, B);Â
Â
// This code is contributed by patel2127Â
</script> |
2
Â
Time Complexity: O(sqrt(B – A))
Auxiliary Space: O(max(A, B))
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



