Least Common Multiple
Given two non-negative integers a and b, compute their least common multiple (LCM). The LCM is the smallest positive integer that is divisible by both a and b.
For example, LCM(4, 6) = 12 because 12 is the smallest number divisible by both 4 and 6. LCM(7, 3) = 21. LCM(0, 5) = 0 (zero is divisible by any number, and by convention LCM with zero is 0). LCM(12, 8) = 24.
The LCM is closely related to the GCD (greatest common divisor) through the formula: LCM(a, b) = |a × b| / GCD(a, b). This relationship means that if you can compute the GCD (using the Euclidean algorithm), you can compute the LCM efficiently without trial division.
Applications of LCM include adding and subtracting fractions (finding a common denominator), scheduling problems (when will two recurring events coincide?), and gear ratio calculations in mechanical engineering.
When implementing, be careful about overflow: a × b can overflow before division by GCD brings it back. One trick is to divide one number by GCD first, then multiply: a / GCD(a, b) * b. This keeps intermediate values smaller. Edge cases include either number being 0 (return 0) and both numbers being equal (the LCM equals either number).
Example Input & Output
Prime pair
Same numbers
LCM of 12 and 8 is 24
Zero
LCM of 4 and 6 is 12
Algorithm Flow

Solution Approach
Use the formula LCM(a, b) = |a × b| / GCD(a, b), computing GCD with the Euclidean algorithm.
First check if either number is 0 and return 0. Then compute the GCD using the Euclidean algorithm. Finally, compute (a / gcd) * b instead of (a * b) / gcd to avoid integer overflow. Dividing a by the GCD first reduces the magnitude of the intermediate value.
For example, LCM(12, 8): GCD(12, 8) = 4. (12 / 4) * 8 = 3 * 8 = 24. This matches the expected result. LCM(7, 3): GCD(7, 3) = 1. (7 / 1) * 3 = 7 * 3 = 21.
Time complexity is O(log min(a, b)) due to the Euclidean algorithm. Space complexity is O(1).
Best Answers
class Solution {
public int solution(int a, int b) {
if(a==0||b==0)return 0;int x=a,y=b;
while(y!=0){int t=y;y=x%y;x=t;}
return Math.abs(a*b)/x;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
