Skip to the solution
EasyDSA7 min read

How do you compute the GCD of two numbers?

672 views

The problem

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 case gcd(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.gcd and math.lcm (both accept any number of arguments since Python 3.9), the tuple swap a, 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.

  • math
  • gcd

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read · 13 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonEuclid with step counts, LCM and a trace
PythonSubtraction vs modulo, Fibonacci worst case, lcm(1..k)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 23 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How do you check if a root-to-leaf path sums to a target?

Continue