Volver a los desafíos
Fácil 0 resueltos 0% de aceptación

Least Common Multiple

Find the smallest positive number divisible by both values.

Lo que aprenderás

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

Problema

Ver traducción

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

Restricciones

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

Ejemplos

Ejemplo 1
Entrada:
a = 4
b = 6

Salida esperada:
expected = 12
Entrada:
long long a = 4;
long long b = 6;

Salida esperada:
long long expected = 12;
Entrada:
long a = 4;
long b = 6;

Salida esperada:
long expected = 12;

Explicación

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

Ejemplo 2
Entrada:
a = 7
b = 7

Salida esperada:
expected = 7
Entrada:
long long a = 7;
long long b = 7;

Salida esperada:
long long expected = 7;
Entrada:
long a = 7;
long b = 7;

Salida esperada:
long expected = 7;

Explicación

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

Cómo abordarlo

Inténtalo primero por tu cuenta y luego abre las pistas una a una.

Pista 1

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

Pista 2

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

Pista 3

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

Complejidad esperada

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

Referencias

Este reto está adaptado para CodeUtility. Sigue el enunciado y las restricciones indicadas arriba.

Aprende de otros

Soluciones de la comunidad

Aún no hay soluciones publicadas. Resuelve este reto para compartir la primera.