Python Program for Basic Euclidean algorithms



Euclidean Algorithm

The Euclidean Algorithm is used to find the Greatest Common Divisor (GCD) of two numbers. The GCD of two integers is the largest number that divides both of them without leaving a remainder.

This algorithm is based on the principle that the GCD of two numbers also divides their difference. The method repeatedly replaces the larger number by the remainder of dividing the larger number by the smaller one, until one of the numbers becomes zero.

Problem Statement

You are given two positive integers a and b. You need to find the greatest common divisor (GCD) of these two numbers using the Euclidean algorithm.

Implementation of Euclidean Algorithm Using Recursive (Brute-force) Approach

Here we solve the GCD problem using a recursive function that keeps applying the rule: gcd(a, b) = gcd(b, a % b) until b becomes 0.

This method breaks down the problem into smaller subproblems and solves them by calling itself recursively.

Steps for the Recursive Approach

  • If b becomes 0, return a.
  • Otherwise, call the function with parameters (b, a % b).
  • Continue until the remainder becomes 0.

Example

In this example, we calculate the GCD of two numbers by recursively calling the function until one number becomes zero -

# Recursive method to find GCD
def gcd(a, b):
   if b == 0:
      return a
   else:
      return gcd(b, a % b)

# Test input
a = 48
b = 18
print(gcd(a, b))

Following is the output obtained -

6

Implementation of Euclidean Algorithm Using Iterative (Bottom-Up) Approach

The recursive method uses stack space, which may cause issues for large inputs. In the iterative method, we avoid recursion and use a loop instead. This makes the solution faster.

We repeatedly assign a = b and b = a % b until b becomes 0. When the loop ends, a will hold the GCD.

Steps for the Iterative Approach

  • Repeat until b becomes 0:
  • Temporarily store b in a variable.
  • Update b as a % b.
  • Set a to the temporarily stored value.
  • When loop ends, return a.

Example

In this example, we use a while loop to keep updating the values of a and b until b becomes 0 -

# Iterative method to find GCD
def gcd(a, b):
   while b != 0:
      a, b = b, a % b
   return a

# Test input
a = 48
b = 18
print(gcd(a, b))

We get the output as shown below -

6

All the variables are declared in the local scope and their references are updated step by step in the loop or recursion.

Updated on: 2025-06-13T18:14:27+05:30

537 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements