Dễ 0 đã giải Tỷ lệ chấp nhận 0%

Least Common Multiple

Find the smallest positive number divisible by both values.

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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).

Ràng buộc

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

Ví dụ

Ví dụ 1
Đầu vào:
a = 4
b = 6

Kết quả mong đợi:
expected = 12
Đầu vào:
long long a = 4;
long long b = 6;

Kết quả mong đợi:
long long expected = 12;
Đầu vào:
long a = 4;
long b = 6;

Kết quả mong đợi:
long expected = 12;

Giải thích

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

Ví dụ 2
Đầu vào:
a = 7
b = 7

Kết quả mong đợi:
expected = 7
Đầu vào:
long long a = 7;
long long b = 7;

Kết quả mong đợi:
long long expected = 7;
Đầu vào:
long a = 7;
long b = 7;

Kết quả mong đợi:
long expected = 7;

Giải thích

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

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

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

Gợi ý 2

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

Gợi ý 3

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

Độ phức tạp mong đợi

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.