Euclidean Algorithm
Euclid's algorithm finds gcd(a, b) by repeatedly replacing (a, b) with (b, a mod b) until the remainder becomes zero.
Beginne mit diesem mentalen Modell
Euclid's algorithm finds gcd(a, b) by repeatedly replacing (a, b) with (b, a mod b) until the remainder becomes zero.
So funktioniert es – ohne unnötigen Jargon
The key property is gcd(a, b) = gcd(b, a mod b).
It is much faster than checking every possible divisor.
Lies den Algorithmus als Folge von Entscheidungen
State the mathematical identity/property.
Choose numeric representation and constraints.
Translate the property into an iterative/recursive computation and analyze precision.
Read a tiny input by hand and write down the state after every important operation. For Euclidean Algorithm, the goal is to make the invariant visible rather than to memorize code.
function gcd(a, b) {
a = Math.abs(a);
b = Math.abs(b);
while (b !== 0) {
[a, b] = [b, a % b];
}
return a;
}Lerne die Syntax nicht auswendig. Folge dem Zustand, der sich in jeder Zeile ändert, und verbinde ihn mit der oben beschriebenen Invariante.
O(log min(a,b))
Do not quote this complexity mechanically. Ask which operation or input dimension it describes, then derive the cost from the loops, recursion depth, data-structure operations and any preprocessing assumptions.
Gut geeignet
- Use the direct mathematical property when it removes unnecessary brute force.
Was typischerweise schiefgeht
- Ignoring floating-point precision or integer range.
- Using a formula outside its valid assumptions.
Struktur einer professionellen Antwort
Explain the invariant/property behind the modulo step; do not present it as a magic loop.
What problem does Euclidean Algorithm solve?
Euclid's algorithm finds gcd(a, b) by repeatedly replacing (a, b) with (b, a mod b) until the remainder becomes zero.
Was sollte ich zur Komplexität erwähnen?
Its typical cost here is O(log min(a,b)), but a complete answer should connect that cost to the representation, input constraints and the dominant operations.
Was ist der häufigste Fehler?
Ignoring floating-point precision or integer range.