Voltar para os desafios
Fácil 0 resolvidos 0% de aceitação

Least Common Multiple

Find the smallest positive number divisible by both values.

O que você vai aprender

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

Problema

Ver tradução

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

Restrições

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

Exemplos

Exemplo 1
Entrada:
a = 4
b = 6

Saída esperada:
expected = 12
Entrada:
long long a = 4;
long long b = 6;

Saída esperada:
long long expected = 12;
Entrada:
long a = 4;
long b = 6;

Saída esperada:
long expected = 12;

Explicação

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

Exemplo 2
Entrada:
a = 7
b = 7

Saída esperada:
expected = 7
Entrada:
long long a = 7;
long long b = 7;

Saída esperada:
long long expected = 7;
Entrada:
long a = 7;
long b = 7;

Saída esperada:
long expected = 7;

Explicação

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

Como abordar

Tente sozinho primeiro e depois abra uma dica de cada vez.

Dica 1

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

Dica 2

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

Dica 3

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

Complexidade esperada

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

Referências

Este desafio foi adaptado para o CodeUtility. Siga o enunciado e as restrições acima.

Aprenda com outros

Soluções da comunidade

Ainda não há soluções publicadas. Resolva este desafio para compartilhar a primeira.