GCD and LCM
Computes the greatest common divisor and the least common multiple.
- Level
- Intermediate
- Topic:
- Math
- Concepts:
- Input & output
- Functions
- Mientras
- Math
Open in Codoritmo
Run, change and debug this example in your browser.
What you'll learn
The MCD Funcion runs Euclid's algorithm with Mientras and MOD. The LCM comes from the GCD, using Trunc to keep a whole number.
Code
Funcion resultado <- MCD(a, b) Definir resultado, resto Como Entero // Algoritmo de Euclides Mientras b <> 0 Hacer resto <- a MOD b a <- b b <- resto FinMientras resultado <- aFinFuncionAlgoritmo MCDyMCM Definir a, b, divisor Como Entero Escribir "Primer número:" Leer a Escribir "Segundo número:" Leer b Si a <= 0 O b <= 0 Entonces Escribir "Usa números enteros positivos." SiNo divisor <- MCD(a, b) Escribir "MCD(", a, ", ", b, ") = ", divisor Escribir "MCM(", a, ", ", b, ") = ", Trunc(a * b / divisor) FinSiFinAlgoritmoFlowchart
Each block in the flowchart matches one instruction in the code.
Sample run
This is what the program shows when it runs. The answers typed by the user are highlighted.
Primer número:User answer: 12Segundo número:User answer: 18MCD(12, 18) = 6MCM(12, 18) = 36
Complexity
How much work and memory it needs as the amount of data (n) grows.
| Case | Cost |
|---|---|
| Best | O(1) |
| Average | O(log n) |
| Worst | O(log n) |
| Memory | O(1) |
Challenge
Ask for three numbers and compute the GCD of all three.
Show hint
The GCD of three numbers is MCD(MCD(a, b), c).
Related examples
Base Conversion
Writes a number in binary and hexadecimal.
AdvancedLinear vs. Binary Search
Counts the comparisons each search needs on the same sorted list.
IntermediateQuadratic Equation
Solves ax² + bx + c = 0, with real or complex roots.
Intermediate