GCD of Two Numbers

Pattern: Maths basics

easy

Find the greatest common divisor with Euclid's method, which replaces the pair (a, b) with (b, a % b) until b is 0.

The problem

You are given two whole numbers a and b, each from 0 up to the 32-bit limit, and not both 0. Return their greatest common divisor (gcd): the largest number that divides both exactly. For example, the gcd of 48 and 18 is 6, and the gcd of 7 and 13 is 1.

On the original site the problem is written a little differently, so use the link above for its exact wording. The function name gcd and the limits above are this guide's own.

Think first

  • List the divisors of 48 and of 18. Which is the largest one they share?
  • If d divides both 48 and 18, must it also divide 48 - 18 = 30? And 48 - 2 × 18 = 12?
  • What is the gcd of a number and 0?

Hints

    Brute force, and why it fails

    Try every candidate from min(a, b) downwards and return the first that divides both. For two large numbers with gcd 1, such as 1,000,000,007 and 999,999,999, that is close to a billion tries.

    Repeated subtraction (replace the bigger number with bigger minus smaller) is correct too, but for (1,000,000,000, 1) it subtracts a billion times.

    The key insight

    gcd(a, b) = gcd(b, a % b), and gcd(a, 0) = a. Taking the remainder does a whole batch of subtractions at once, and the numbers shrink so fast that even 32-bit inputs need only a few dozen rounds.

    Dry run

    480 
    181 
    a48
    b18

    a = 48 and b = 18. b is not 0, so keep going. The array shows the current pair.

    Step 1 of 5

    The plan

    while b != 0:
        remainder = a mod b
        a = b
        b = remainder
    return a
    

    Complexity

    Time
    O(log(min(a, b)))
    Space
    O(1)

    The smaller number at least halves every two rounds, so the number of rounds grows with the number of digits, not with the size. For 32-bit inputs it is under 50 rounds.

    Edge cases

    • gcd(a, 0) = a and gcd(0, b) = b. The loop handles both.
    • Equal numbers: gcd(100, 100) = 100.
    • Numbers with no common factor give 1, such as gcd(7, 13).
    • The order does not matter: gcd(18, 48) takes one extra round and also gives 6.
    I've built my logic, show the code

    Java

    class Solution {
        public int gcd(int a, int b) {
            while (b != 0) {
                int remainder = a % b;
                a = b;
                b = remainder;
            }
            return a;
        }
    }

    C++

    class Solution {
    public:
        int gcd(int a, int b) {
            while (b != 0) {
                int remainder = a % b;
                a = b;
                b = remainder;
            }
            return a;
        }
    };

    Python

    class Solution:
        def gcd(self, a, b):
            while b != 0:
                a, b = b, a % b
            return a

    Common mistakes

    • Computing a % b without first checking that b is not 0.
    • Returning b at the end, which is always 0 there.
    • Overwriting a before computing the remainder, so the old a is lost. Compute the remainder first, as in the plan.

    Similar problems