Dynamic Programming21 sections · 916 units
Open in Course

GCD - The Key Observation

Why modulo works

Here is the observation: gcd(a,b)=gcd(b,amodb)\gcd(a, b) = \gcd(b, a \bmod b). Why does this work? If dd divides both aa and bb, then dd also divides aba - b, and a2ba - 2b, and so on. The remainder amodba \bmod b is just aa minus some multiple of bb.

So any common divisor of aa and bb is also a common divisor of bb and amodba \bmod b. This means you can replace the larger number with a remainder, making the problem smaller each time. The numbers shrink fast.

unnamed (12) (1).jpg