Article start
DSA Course: Interview Patterns and Problem Solving
Module 15: Math & Number Theory

GCD: Euclidean Remainder Pattern

Find the greatest common divisor using repeated remainders.

May 29, 2026·24

Learning Outcome

After this lesson, you should be able to replace gcd(a,b) with gcd(b,a mod b) until the remainder becomes zero.

Problem Statement

Given two integers a and b, return their greatest common divisor.

InputOutputWhy
a = 56, b = 981414 is the largest number that divides both 56 and 98.

Brute Force Approach

Check every possible divisor from min(a,b) down to 1. This can be slow when numbers are large.

Optimized Approach

Use the identity gcd(a,b) = gcd(b,a mod b). Repeated remainders shrink the numbers quickly.

Exact Pseudocode

while b is not 0:
  remainder = a % b
  a = b
  b = remainder
return absolute value of a

Reference Code

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

Sample Dry Run

StepStateResult
Starta = 56, b = 98continue
Step 156 % 98 = 56a = 98, b = 56
Step 298 % 56 = 42a = 56, b = 42
Finish56 % 42 = 14, 42 % 14 = 0return 14

Complexity

MeasureValueReason
TimeO(log min(a,b))The Euclidean remainder sequence shrinks quickly.
SpaceO(1)Only a few integer variables are stored.

Edge Cases

  • gcd(a,0) is absolute value of a.
  • gcd(0,b) is absolute value of b.
  • Normalize negative inputs with absolute value at the end.

Interview Checklist

  • Use modulo, not repeated subtraction.
  • Stop when the second value becomes zero.
  • Return the nonzero value as positive.

FAQs

Why does gcd(a,b) equal gcd(b,a mod b)?

Any divisor of a and b also divides the remainder after removing multiples of b.

Why is modulo faster than subtraction?

Modulo removes many repeated subtraction steps in one operation.

What is the core pattern?

Euclidean remainder reduction.

Test your knowledge

Take a quick quiz based on this chapter.

mediumDSA Course
GCD - Euclidean Remainder Pattern Practice Quiz
5 questions8 min

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.