Python GCD of Two Numbers Program

Beginner
6 min read
Updated: Oct 2026
3 programs
Live preview

What Is GCD?

The GCD (Greatest Common Divisor), also called HCF, is the largest positive integer that divides both numbers with no remainder.

Remember
gcd(a, b) = largest d > 0 such that
            a % d == 0 and b % d == 0

Example: gcd(48, 18) = 6
  48 = 6 * 8
  18 = 6 * 3
  No larger positive integer divides both
abgcd(a, b)
48186
17131
02121
-12186

How to Find GCD in Python

Four clear steps — Euclid’s remainder loop is the interview default.

  1. Take absolute values of a and b so the result is nonnegative.
  2. While b != 0, replace (a, b) with (b, a % b).
  3. When b becomes 0, return a — that is the GCD.
  4. Optionally derive LCM with abs(a // gcd * b), or use math.gcd in real code.
MethodIdeaTimeBest for
Iterative EuclidLoop with a % b until b == 0O(log min)Interviews, production default
Recursive Euclidgcd(b, a % b) until base caseO(log min)Showing the recurrence
LCM via GCDabs(a // g * b)O(log min)Follow-up questions

Pseudocode

Pseudocode
function gcd(a, b):
    a = abs(a)
    b = abs(b)

    while b != 0:
        a, b = b, a mod b

    return a

function lcm(a, b):
    if a == 0 or b == 0:
        return 0
    return abs(a // gcd(a, b) * b)

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
Core stepa, b = b, a % b
Stop whenb == 0; answer is a
SignsUse abs() first
gcd(0, n)abs(n) for n != 0
gcd(0, 0)Usually defined as 0
Builtinmath.gcd(a, b)
LCM linkabs(a // g * b)
Classic checkgcd(48, 18) = 6

Live Preview

Enter two integers to see the Euclidean remainder chain and the GCD.

Whole numbers only. Tap a chip or type a pair.

Result
a = 48, b = 18
Chain: (48, 18) → (18, 12) → (12, 6) → (6, 0)
gcd = 6

Worked Walkthrough — gcd(48, 18)

Apply Euclid’s step until the remainder is zero.

Calculation
Start: a = 48, b = 18

Step 1: 48 % 18 = 12  → (18, 12)
Step 2: 18 % 12 = 6   → (12, 6)
Step 3: 12 % 6  = 0   → (6, 0)

Stop (b == 0)
gcd(48, 18) = 6

Check: 48 / 6 = 8,  18 / 6 = 3

Python Programs

Start with the iterative loop — it is the clearest interview answer. Then show the recursive form, and finish with LCM built from GCD.

Example 1 — Iterative Euclidean Algorithm

Loop with remainders until the second value becomes zero.

python
def find_gcd(a, b):
    a, b = abs(a), abs(b)

    while b != 0:
        a, b = b, a % b

    return a


number1 = 48
number2 = 18
print(f"GCD of {number1} and {number2} is: {find_gcd(number1, number2)}")

How It Works

  1. Take absolute values so negatives do not break the remainder chain.
  2. While b != 0, swap with a remainder: a, b = b, a % b.
  3. For (48, 18) the pairs become (18, 12), (12, 6), then (6, 0).
  4. When b is 0, return a — here 6.
  5. Extra space is O(1); time is logarithmic in the smaller number.

Example 2 — Recursive Euclidean Algorithm

Same remainder idea, written as a recurrence with a clear base case.

python
def find_gcd(a, b):
    a, b = abs(a), abs(b)

    if b == 0:
        return a

    return find_gcd(b, a % b)


number1 = 48
number2 = 18
print(f"GCD of {number1} and {number2} is: {find_gcd(number1, number2)}")

How It Works

  1. Base case: if b == 0, return a.
  2. Otherwise recurse on find_gcd(b, a % b).
  3. Calls for (48, 18): (18, 12) → (12, 6) → (6, 0) → return 6.
  4. Same answer as the loop; stack depth is about O(log min(a, b)).
  5. Prefer the iterative version when you must mention space carefully.

Example 3 — LCM via GCD

Use the identity lcm(a, b) = abs(a // gcd * b) after finding the GCD.

python
def find_gcd(a, b):
    a, b = abs(a), abs(b)
    while b != 0:
        a, b = b, a % b
    return a


def find_lcm(a, b):
    if a == 0 or b == 0:
        return 0
    g = find_gcd(a, b)
    return abs(a // g * b)


a = 48
b = 18
print(f"gcd = {find_gcd(a, b)}")
print(f"lcm = {find_lcm(a, b)}")

How It Works

  1. Reuse the same iterative find_gcd helper.
  2. If either input is 0, LCM is defined as 0 here.
  3. Divide by the GCD first: a // g * b keeps intermediates smaller.
  4. abs(...) keeps the LCM nonnegative for negative inputs.
  5. Check: 48 // 6 * 18 = 8 * 18 = 144, and 144 / 48 = 3, 144 / 18 = 8.

Edge Cases & Pitfalls

Check these before calling the solution done.

Zero

gcd(0, n)

For n != 0, the answer is abs(n). Euclid already handles this.

Both zero

gcd(0, 0)

Conventionally return 0. Say your choice out loud in interviews.

Negatives

Use abs()

Normalize signs first so the returned GCD is nonnegative.

LCM

Divide before multiply

Prefer a // gcd * b over a * b // gcd when values can get large.

Time and Space Complexity

ProgramTimeExtra space
Iterative EuclidO(log min(a, b))O(1)
Recursive EuclidO(log min(a, b))O(log min(a, b))
LCM via GCDO(log min(a, b))O(1)

Worst-case Euclid pairs are consecutive Fibonacci numbers, but the step count still grows logarithmically.

Key Takeaways

  • Definition: largest positive integer that divides both values.
  • Euclid: a, b = b, a % b until b == 0.
  • LCM: abs(a // gcd * b) after finding the GCD.
  • Test set: (48, 18) → 6; (17, 13) → 1; (0, 21) → 21.

One line: keep taking remainders — when the remainder hits zero, the other value is the GCD.

Frequently Asked Questions

The greatest common divisor (also called HCF) is the largest positive integer that divides both numbers without a remainder.
Replace (a, b) with (b, a % b) until b becomes 0. Then a is the GCD. Always take absolute values first.
For n != 0, gcd(0, n) equals |n|. By convention, many libraries (including math.gcd) define gcd(0, 0) as 0.
Yes in real projects. In interviews, write Euclid yourself first, then mention math.gcd.
For nonzero a and b: lcm(a, b) = abs(a * b) // gcd(a, b). Prefer abs(a // g * b) to keep intermediates smaller.

Next: Happy Number

Check whether repeated digit-square sums reach 1.

Happy number tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful