DryRun
AlgorithmsCourseCompare
DryRun
AlgorithmsCourseCompareGitHubLinkedIn

© 2026 DryRun. Built by Aditya Pandey.

AlgorithmsAdvancedEuclid Algorithm (GCD)
Advancedbeginnernumber-theorygcdmodulofundamentals

Euclid Algorithm (GCD)

Euclid's algorithm finds gcd(a, b) by repeatedly replacing (a, b) with (b, a mod b) until b becomes zero. The remaining a is the gcd. This method is fast, elegant, and foundational for modular arithmetic and cryptography.

Complexity

Best
O(log n)
Average
O(log n)
Worst
O(log n)
Space
O(1)

Implementation

int gcd(int a, int b) {
    while (b != 0) {
        int r = a % b;
        a = b;
        b = r;
    }
    return abs(a);
}

How It Works

1.Core Idea

gcd(a, b) equals gcd(b, a mod b). Repeating this reduction quickly shrinks the numbers.

2.Termination

Remainders strictly decrease and eventually become zero, so the loop always terminates.

3.Why It Matters

Used in modular inverses, CRT, and many competitive programming and cryptography routines.

Related Algorithms

CpuChinese Remainder TheoremSearchBinary Search

Test Your Knowledge

Quiz coming soon for this algorithm.

Back to all algorithms