LCM of Two Numbers

medium Number Problems

Problem

Read two non-negative integers on one line. Print their least common multiple (LCM): the smallest positive number that both numbers divide. If one number is 0, print 0.

Constraints

  • 0 <= a, b <= 10^9

Examples

Input

4 6

Output

12

Solutions

Best approachTime O(log(min(a, b)))Space O(1)

For two numbers, gcd(a, b) * lcm(a, b) = a * b. So we find the GCD and calculate the LCM. We divide before we multiply to keep the numbers small.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Find the least common multiple (LCM) of two numbers.
 * Input   : Two non-negative integers on one line.
 * Output  : Their LCM.
 * Approach: Use LCM = a / gcd(a, b) * b.
 * Time    : O(log(min(a, b)))
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method receives two numbers and returns their GCD with the Euclidean algorithm.
    static long gcd(long first, long second) {
        while (second != 0) {
            long remainder = first % second;
            first = second;
            second = remainder;
        }
        return first;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long first = scanner.nextLong();
        long second = scanner.nextLong();

        // Step 1: If one number is 0, the LCM is 0. We stop here to avoid a division by zero.
        if (first == 0 || second == 0) {
            System.out.println(0);
            return;
        }

        // Step 2: Use the rule gcd * lcm = a * b. So lcm = a / gcd * b.
        // We divide first, so the number stays small and does not overflow.
        long lcm = first / gcd(first, second) * second;

        // Step 3: Print the result.
        System.out.println(lcm);
    }
}
Hints (2)
  1. Use the GCD you already know.
  2. gcd * lcm = a * b