Question presented to candidate: "Write a Python function that returns the greatest common divisor of two integers. Explain why your method is correct and how fast it is, and tell me how you would get the least common multiple."
What a strong answer should cover:
- The brute-force idea (try every divisor, O(min(a, b))) and why Euclid is better.
- Euclid's algorithm
gcd(a, b) = gcd(b, a % b)with base casegcd(a, 0) = a, and the reason: common divisors of (a, b) and (b, a mod b) are the same. - O(log min(a, b)) steps, worst case consecutive Fibonacci numbers; iterative O(1) space vs recursive O(log n) stack.
- LCM as
a // gcd(a, b) * b(divide first), and zero/negative inputs. - Python details:
math.gcdandmath.lcm(both accept any number of arguments since Python 3.9), the tuple swapa, b = b, a % b,%takes the sign of the divisor, and ints never overflow.
Clarifying questions expected:
- Can inputs be negative or zero?
- Is the LCM needed as well?
Code / implementation expected: Yes — an iterative Euclid in Python 3, then a mention of math.gcd.