簡単 0件解決済み 正答率0%

Least Common Multiple

Find the smallest positive number divisible by both values.

このチャレンジで学べること

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

問題

翻訳を表示

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

例

例 1
入力:
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.

例 2
入力:
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用に調整されています。上記の説明と制約に従ってください。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。