問題
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).
制約
1 ≤ a, b ≤ 1,000,000,000
例
入力:
a = 4
b = 6
期待される出力:
expected = 12
入力:
long long a = 4;
long long b = 6;
期待される出力:
long long expected = 12;
入力:
long a = 4;
long b = 6;
期待される出力:
long expected = 12;
解説
Multiples of 4: 4, 8, 12…; multiples of 6: 6, 12…; the first common one is 12.
入力:
a = 7
b = 7
期待される出力:
expected = 7
入力:
long long a = 7;
long long b = 7;
期待される出力:
long long expected = 7;
入力:
long a = 7;
long b = 7;
期待される出力:
long expected = 7;
解説
A number's LCM with itself is the number: 7.
解き方のヒント
まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。
ヒント 1
Use the relationship between gcd and lcm instead of searching for multiples.
ヒント 2
Compute the gcd first, then combine the two numbers carefully.
ヒント 3
Divide before multiplying to reduce overflow risk, even with large inputs.
目安の計算量
O(log min(a, b)) time, O(1) extra space
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。