PPractick

DSA interview question

GCD of Two Numbers

Easy · Algorithms · Topics: basic maths, number theory, euclidean algorithm

The problem

A tiling app lets users cover an a × b floor with identical square tiles and wants the largest square tile that fits perfectly with no cutting. That's the Greatest Common Divisor (GCD) of the two sides. The same function is needed to simplify fractions and compute the least common multiple for scheduling repeating events. Checking every candidate divisor works but is far too slow for values up to 10^9; Euclid's algorithm, over 2,000 years old, solves it in a handful of steps.

Example: gcd(48, 180) = 12, so a 48 × 180 floor takes 12 × 12 tiles.

Function signature

long long gcd(long long a, long long b);  // greatest common divisor, a, b >= 0, not both 0
long long lcm(long long a, long long b);  // least common multiple, a, b > 0

Test cases

Input (a, b)OutputExplanation
(12, 18)6Largest number dividing both
(48, 180)12
(7, 13)1Coprime numbers
(100, 25)25One divides the other
(0, 5)5gcd(0, b) = b
(1, 1)1
(1000000000, 999999999)1Consecutive integers are coprime; Euclid needs very few steps
lcm(4, 6)12lcm = a / gcd × b

(Confirm: inputs are non-negative and not both zero; values up to 10^9.)

How interviewers phrase it

Clarifying questions to ask

  1. Can the numbers be zero or negative?
  2. What's the range? (Decides whether brute force is acceptable.)
  3. Is the LCM also needed, and could it overflow?

Follow-ups to expect

  1. "Why does gcd(a, b) = gcd(b, a % b) hold?"
  2. "What's the complexity of Euclid's algorithm?"
  3. "What about the brute-force approach?"
  4. "How do you compute the LCM safely?"
  5. "Is there a built-in?"
  6. "GCD of an array?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in