Euclidean Algorithm Explained: Visual Guide, and Real Examples

euclidean-algorithm-feature.jpg

The Euclidean algorithm is a classic and efficient method for finding the greatest common divisor (GCD) of two numbers. It’s one of the oldest algorithms still in use—first described by the Greek mathematician Euclid (also happened to be the Father of Geometry) in his book Elements, all the way back in 300 BC.

The GCD (short for greatest common divisor) of two whole numbers is simply the largest positive number that divides both of them without leaving a remainder. In programming, this is typically implemented using either recursion or iteration, where we repeatedly divide and take the remainder until we hit zero.

Now, if you happened to be snoozing during your elementary school math lessons (no judgment, we’ve all been there), don’t worry. This article will walk you through a real example, show how the method works visually and geometrically, and brush up your understanding of this timeless technique. And for the coders among us, we’ll also include working code snippets in major programming languages.

Table of Contents:

Euclidean Algorithm for Greatest Common Divisor (GCD)

Let’s say we have two integers – 48 and 18. 

We want to find their GCD using the Euclidean algorithm.

Step 1: Divide the larger number by the smaller one

Quick Math Fact:

48 ÷ 18 = 2 remainder 12

So we write it like this:
48 = 2 × 18 + 12

Now, take the divisor (18) and the remainder (12) and repeat the process.

Step 2: Repeat with the previous divisor and remainder

Quick Math Fact:

18 ÷ 12 = 1 remainder 6  → 18 = 1 × 12 + 6

Step 3: One more round

Quick Math Fact:

12 ÷ 6 = 2 remainder 0  → 12 = 2 × 6 + 0

We’ve hit a remainder of 0, so we stop here.

The last non-zero remainder was 6, so GCD(48, 18) = 6

What You Just Did: Euclidean Algorithm In Formal Notation

The Euclidean algorithm always follows this structure:

euclidean-formal-notation

Where:

  • a₀ is the larger number
  • b is the smaller number
  • q₀ is the quotient (how many times b fits into a)
  • r is the remainder

You keep replacing a with b, and b with r, like this:

a₀ = q₀b₀ + r₀  
b₀ = q₁r₀ + r₁ (first iteration)  
r₀ = q₂r₁ + r₂ (final iteration)  
… until the remainder is 0

We keep repeating the k-steps interactive process until the remainder becomes zero. The last non-zero remainder is the GCD. In our example:

48 = 2 × 18 + 12  
18 = 1 × 12 + 6  
12 = 2 × 6 + 0  
→ GCD = 6

This is the Euclidean algorithm formula in action.
Next, we’ll show it as a visual flow so you can see how the remainders drive the process.

Walking the Algorithm Visually 

To bring more clarity on the subject, let’s take a visual walk through the Euclidean Algorithm. 

Let’s imagine a rectangle: 48 units long, 18 units wide

Think of it like a field. You want to tile this field perfectly using square tiles.
But not just any size — you want the biggest square that fits evenly.

biggest-square-fits

Step 1: Try 18×18 squares

Start by laying 18×18 squares along the 48-unit side.

You can fit two full squares (18 + 18 = 36), but you’re still left with 12 units of extra space.

That leftover 12×18 area is your new rectangle.

square-step-second

Step 2: Move to the leftover part (12×18)

Now ask — how many 12×12 squares fit along the 18-unit width?

You get one full square, with 6 units left over.

So now your remaining area is 6×12.

square-step-fourth

Step 3: Tile the 6×12 area

Fit 6×6 squares into the 12-unit length.
You get two perfect squares, no leftovers.

We’ve hit a clean fit. That’s your stopping point.

square-step-third

Implementing the Euclidean Algorithm in Modern Programming Languages

Euclid didn’t have Python or JavaScript, but the brilliance of his method still shines through in modern code. The heart of the Euclidean Algorithm is simple: keep dividing and replacing until the remainder becomes zero.

  1. Python
def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a

print(gcd(48, 18))  
  1. JavaScript
function gcd(a, b) {
  while (b !== 0) {
    let temp = b;
    b = a % b;
    a = temp;
  }
  return a;
}

console.log(gcd(48, 18));
  1. C Programming Language 
#include <stdio.h>

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

int main() {
    printf("%d\n", gcd(48, 18));  // Output: 6
    return 0;
}
  1. C++ 
#include <iostream>
using namespace std;

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

int main() {
    cout << gcd(48, 18) << endl;  // Output: 6
    return 0;
}
  1. C#
using System;

class Program {
    static int GCD(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }

    static void Main() {
        Console.WriteLine(GCD(48, 18));  // Output: 6
    }
}
  1. JAVA
public class GCD {
    public static int gcd(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }

    public static void main(String[] args) {
        System.out.println(gcd(48, 18));  // Output: 6
    }
}
Quick Note on the mod Operation

The mod operation gives the remainder when one number is divided by another. We write it as:
A mod B = R → when A is divided by B, the remainder is R.

48 mod 18 = 12 → because 18 fits into 48 twice (2 × 18 = 36), and 48 − 36 = 12

In code, this is written using the % operator:
Python: a % b

JavaScript: a % b

C, C++, Java, C#: a % b

This simple operation drives the Euclidean Algorithm’s step-by-step reduction.

What’s the Extended Euclidean Algorithm, and Why It Matters

The basic Euclidean algorithm helps you find the GCD of two numbers. But the Extended Euclidean Algorithm takes it a step further — it finds how that GCD can be written using the original numbers themselves.

In other words, it gives you integers x and y such that:

ax + by = gcd(a, b)

What does that mean?

Let’s go back to our running example:

We know:

GCD(48, 18) = 6

Now here’s the twist: the extended version tells us that you can write 6 as a combination of 48 and 18.

One valid solution is:

6 = (-1)×48 + 3×18

Therefore: 

  • x = -1
  • y = 3

That’s what the Extended Euclidean Algorithm does — it shows how the GCD is stitched together from the two original numbers.

This isn’t just mathematical trivia.

This equation — ax + by = gcd(a, b) — is exactly what you need when working with:

  • Modular inverses (e.g., solving ax ≡ 1 mod m)
  • Key generation in RSA
  • Diophantine equations
  • And more broadly, Euclidean algorithm cryptography

If the classic version helps you divide things cleanly, the extended version lets you undo modular operations, which is essential in cryptography and secure systems.

Real-Life Applications of the Euclidean Algorithm: Why You Should Care

The Euclidean Algorithm isn’t just a mathematical relic. It quietly supports a surprising range of things — from simplifying ratios to powering secure communication.

If you’re a student learning how things connect, or a developer working on something as complex as encryption or as simple as layout engines, this one algorithm is worth having in your mental toolbox. It’s small, sharp, and surprisingly powerful.

applications-of-the-euclidean-algorithm

1. Simplifying Ratios

Whenever you reduce a ratio like 48:18 to its simplest form (which is 8:3), you’re really using the Euclidean Algorithm behind the scenes.

How? By finding the GCD of the two numbers and dividing both sides by it:

GCD(48, 18) = 6 → (48 ÷ 6) : (18 ÷ 6) = 8 : 3

This is used in:

  • Graphics (resizing images proportionally)
  • Music software (normalizing beat patterns)
  • Cooking apps (scaling recipes up or down)

It’s one of those quiet mathematical steps that make user-facing tools feel seamless.

2. Modular Arithmetic (And Everything Built On It)

The core of modular arithmetic — clock math, hash functions, secure keys — often needs operations like:

Find x such that (a × x) ≡ 1 mod m

You can’t solve this without finding the modular inverse, and the only way to compute that efficiently is the Extended Euclidean Algorithm.

This shows up in:

  • Scheduling systems
  • Game development logic
  • Blockchain consensus rules
  • Financial models using modular math (like EMI tables or tax logic)

For bit-level comparisons, methods like Hamming Distance are used in fields such as error detection and binary data analysis. It approaches difference from a binary perspective rather than through arithmetic remainders.

3. Cryptography: The Algorithm Behind the Locks

The Euclidean Algorithm — especially its extended version — is essential in building public-key cryptosystems like RSA.

Here’s how:

  • It’s used to generate keys (finding values that satisfy modular inverse relationships)
  • It powers digital signatures
  • It ensures private keys can’t be easily reversed, yet allows legitimate parties to decrypt using math

In short, no Euclidean algorithm = no secure communication on the internet.

This is why it’s often taught in cybersecurity courses, and why it appears in algorithms behind HTTPS, encrypted messaging apps, and banking protocols.

4. Compiler Optimizations & Instruction Scheduling

Modern compilers use variants of the Euclidean Algorithm for:

  • Loop optimization (e.g., aligning iteration steps with GCDs)
  • Register allocation where resource matching depends on GCD-related constraints
  • Integer division simplifications using Euclid’s logic

Even things like resolving dependency graphs or optimizing how tasks are parallelized can lean on GCD calculations, especially in embedded systems or low-level firmware development.

So even though you don’t see it, the Euclidean Algorithm helps your code run smarter and faster under the hood.

Closing Notes

The Euclidean Algorithm is one of those rare ideas that’s both ancient and quietly modern. It doesn’t try to impress you with complexity. It simply works. Whether you’re reducing a ratio, optimizing a loop, or securing encrypted data, its logic holds steady.

What makes it timeless isn’t just how simple it is. It’s the way it keeps showing up in real problems. Once you understand how it works, you start noticing it in clean code, in efficient systems, and in the logic behind things that used to feel tough until they suddenly made sense. Perhaps, try it with different integers to retain the concept. 

If you’ve followed the examples, visualized the rectangles, and tried the code, you’ve already got it. You now understand one of the most useful building blocks in both math and computing.

To explore how foundational algorithms like this one connect with data structures and real-world coding problems, you can check out this free C Data Structures course.

It’s a solid next step if you’re building up your problem-solving toolkit.

Euclidean Algorithm – FAQs

1. What is the Euclidean Algorithm, and how does it work?

The Euclidean Algorithm is a method for finding the greatest common divisor (GCD) of two integers. It works by repeatedly dividing the larger number by the smaller one and replacing the numbers with the divisor and the remainder, until the remainder becomes zero. The last non-zero remainder is the GCD.
Covers: Euclidean algorithm, Euclidean algorithm GCD

2. Can you give a simple Euclidean algorithm example?

Sure. Let’s find GCD(252, 105) using the Euclidean algorithm.
252 ÷ 105 = 2 remainder 42

105 ÷ 42 = 2 remainder 21

42 ÷ 21 = 2 remainder 0

The last non-zero remainder is 21, so: GCD(252, 105) = 21

3. What is the Euclidean algorithm formula?

The formula is:
GCD(a, b) = GCD(b, a mod b)
Repeat the steps until the second number becomes 0. This formula is the foundation of both recursive and iterative implementations.

4. What is the Extended Euclidean Algorithm used for?

The Extended Euclidean Algorithm not only finds the GCD of two numbers but also returns integers x and y such that ax + by = gcd(a, b). This is useful for solving modular inverse problems and is widely used in cryptographic systems like RSA.

5. How is the Euclidean algorithm used in cryptography?

In cryptography, especially in RSA, the Euclidean and Extended Euclidean Algorithms are used to compute modular inverses, generate private keys, and validate public key pairs. They ensure secure communication by solving equations within modular arithmetic.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner