Back to challenges
Easy 0 solved 0% acceptance

Least Common Multiple

Find the smallest positive number divisible by both values.

What you'll learn

  • Compute the LCM from the GCD
  • Avoid overflow by dividing before multiplying
  • Reuse one function inside another

Problem

Return the least common multiple of a and b, the smallest positive number that both divide. lcm(a, b) = a / gcd(a, b) × b.

Implement lcm(a, b).

Input

a: The first positive number. b: The second positive number.

Output

Return lcm(a, b).

Constraints

1 ≤ a, b ≤ 1,000,000,000

Examples

Example 1
Input:
a = 4
b = 6

Expected output:
expected = 12
Input:
long long a = 4;
long long b = 6;

Expected output:
long long expected = 12;
Input:
long a = 4;
long b = 6;

Expected output:
long expected = 12;

Explanation

Multiples of 4: 4, 8, 12…; multiples of 6: 6, 12…; the first common one is 12.

Example 2
Input:
a = 7
b = 7

Expected output:
expected = 7
Input:
long long a = 7;
long long b = 7;

Expected output:
long long expected = 7;
Input:
long a = 7;
long b = 7;

Expected output:
long expected = 7;

Explanation

A number's LCM with itself is the number: 7.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Use the relationship between gcd and lcm instead of searching for multiples.

Hint 2

Compute the gcd first, then combine the two numbers carefully.

Hint 3

Divide before multiplying to reduce overflow risk, even with large inputs.

Expected complexity

O(log min(a, b)) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.