Finding GCD of two numbers using Euclidean Algorithm

Finding GCD of two numbers using Euclidean Algorithm


The article explain on finding the algorithm, flowchart, pseudocode and implementation of Euclidean Algorithm to find the GCD of two numbers. Also, it contains implementation of the same in C, Java and Python.

Euclidean Algorithm

Euclidean Algorithm is an efficient method for computing the greatest common divisor (GCD) of two numbers, the largest number that divides both of them without leaving a remainder.

The Euclidean Algorithm is based on the principle that the greatest common divisor of two numbers does not change if the larger number is replaced by its difference with the smaller number.

For example, 21 is the GCD of 252 and 105 (as 252 = 21 × 12 and 105 = 21 × 5), and the same number 21 is also the GCD of 105 and 252 − 105 = 147. Since this replacement reduces the larger of the two numbers, repeating this process gives successively smaller pairs of numbers until the two numbers become equal. When that occurs, they are the GCD of the original two numbers.

By reversing the steps, the GCD can be expressed as a sum of the two original numbers each multiplied by a positive or negative integer, e.g., 21 = 5 × 105 + (−2) × 252.

For more information, refer Wikipedia.

Logic

  1. Take two numbers a and b as input. a should be greater than b else swap them.
  2. Divide a by b and store the remainder in r.
  3. If r is 0, then b is the GCD of a and b.
  4. Else, assign b to a and r to b and repeat from step 2.
  5. Stop.

Flowchart

Euclidean Algorithm Flowchart

Pseudocode

BEGIN
    INPUT a, b
    IF a < b THEN
        SWAP a, b
    END IF
    WHILE b != 0 DO
        r = a % b
        a = b
        b = r
    END WHILE
    PRINT a
END

Implementation

C

#include <stdio.h>

int main() {
    int a, b, r;
    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);
    if (a < b) {
        int temp = a;
        a = b;
        b = temp;
    }
    while (b != 0) {
        r = a % b;
        a = b;
        b = r;
    }
    printf("GCD is %d", a);
    return 0;
}

Java

import java.util.Scanner;

public class EuclideanAlgorithm {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter two numbers: ");
        int a = sc.nextInt();
        int b = sc.nextInt();
        if (a < b) {
            int temp = a;
            a = b;
            b = temp;
        }
        while (b != 0) {
            int r = a % b;
            a = b;
            b = r;
        }
        System.out.println("GCD is " + a);
        sc.close();
    }
}

Python

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
if a < b:
    a, b = b, a
while b != 0:
    r = a % b
    a = b
    b = r
print("GCD is", a)