Euclidean Algorithm
Euclid's algorithm finds gcd(a, b) by repeatedly replacing (a, b) with (b, a mod b) until the remainder becomes zero.
Start with this mental model
Euclid's algorithm finds gcd(a, b) by repeatedly replacing (a, b) with (b, a mod b) until the remainder becomes zero.
How it works, without unnecessary jargon
The key property is gcd(a, b) = gcd(b, a mod b).
It is much faster than checking every possible divisor.
Read the algorithm as a sequence of decisions
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;
}Do not memorize the syntax. Follow the state that changes on each line and connect it to the invariant described above.
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.
Good fit
- Use the direct mathematical property when it removes unnecessary brute force.
What usually goes wrong
- Ignoring floating-point precision or integer range.
- Using a formula outside its valid assumptions.
A professional answer shape
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.
What should I mention about complexity?
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.
What is the most common mistake?
Ignoring floating-point precision or integer range.