Torna alle sfide
Facile 0 risolte 0% di accettazione

Least Common Multiple

Find the smallest positive number divisible by both values.

Cosa imparerai

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

Problema

Mostra traduzione

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

Vincoli

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

Esempi

Esempio 1
Input:
a = 4
b = 6

Output atteso:
expected = 12
Input:
long long a = 4;
long long b = 6;

Output atteso:
long long expected = 12;
Input:
long a = 4;
long b = 6;

Output atteso:
long expected = 12;

Spiegazione

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

Esempio 2
Input:
a = 7
b = 7

Output atteso:
expected = 7
Input:
long long a = 7;
long long b = 7;

Output atteso:
long long expected = 7;
Input:
long a = 7;
long b = 7;

Output atteso:
long expected = 7;

Spiegazione

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

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

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

Suggerimento 2

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

Suggerimento 3

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

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.