What is GCD
Return the greatest common divisor of a and b. gcd(a, 0) = a, so gcd(0, 0) = 0.
Example. gcd(48, 18) returns 6. The remainders are 12, then 6, then 0.
Input: 48 18 Output: 6
Constraints. 0 ≤ a, b ≤ 109. This picture caps each value at 100000.
Approach
b == 0, every previous remainder has been consumed. Return a.gcd(a, b) = gcd(b, a % b). The new second argument is strictly smaller, so the chain ends.Recursion tree
The whole tree is drawn when the page opens. Next and Play start again from the first call.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(log min(a, b)) | The remainder shrinks at every step. |
| Stack | O(log min(a, b)) | One pending call per remainder. |
Implementation
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)