Dynamic Programming21 sections · 915 units
Open in Course

GCD - The Key Observation

Why modulo works

Here is the observation: gcd⁡(a,b)=gcd⁡(b,a mod b)\gcd(a, b) = \gcd(b, a \bmod b). Why does this work? If dd divides both aa and bb, then dd also divides a−ba - b, and a−2ba - 2b, and so on. The remainder a mod ba \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 a mod ba \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