C Program for Basic Euclidean algorithms?

The Euclidean algorithm is an efficient method for finding the Greatest Common Divisor (GCD) of two integers. It works by repeatedly applying the principle that GCD(a,b) = GCD(b, a mod b) until one of the numbers becomes zero.

Syntax

int euclideanGCD(int a, int b);

Algorithm

The recursive Euclidean algorithm follows these steps −

begin
    if a is 0, then
        return b
    end if
    return euclideanGCD(b mod a, a)
end

Method 1: Recursive Approach

This method uses recursion to implement the Euclidean algorithm −

#include <stdio.h>

int euclideanGCD(int a, int b) {
    if (a == 0)
        return b;
    return euclideanGCD(b % a, a);
}

int main() {
    int num1 = 48, num2 = 18;
    printf("Numbers: %d and %d<br>", num1, num2);
    printf("GCD using Euclidean algorithm: %d<br>", euclideanGCD(num1, num2));
    
    num1 = 60; num2 = 36;
    printf("Numbers: %d and %d<br>", num1, num2);
    printf("GCD using Euclidean algorithm: %d<br>", euclideanGCD(num1, num2));
    
    return 0;
}
Numbers: 48 and 18
GCD using Euclidean algorithm: 6
Numbers: 60 and 36
GCD using Euclidean algorithm: 12

Method 2: Iterative Approach

This method uses a loop instead of recursion −

#include <stdio.h>

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

int main() {
    int num1 = 48, num2 = 18;
    printf("Numbers: %d and %d<br>", num1, num2);
    printf("GCD using iterative Euclidean algorithm: %d<br>", euclideanGCDIterative(num1, num2));
    
    num1 = 105; num2 = 30;
    printf("Numbers: %d and %d<br>", num1, num2);
    printf("GCD using iterative Euclidean algorithm: %d<br>", euclideanGCDIterative(num1, num2));
    
    return 0;
}
Numbers: 48 and 18
GCD using iterative Euclidean algorithm: 6
Numbers: 105 and 30
GCD using iterative Euclidean algorithm: 15

How It Works

The algorithm is based on the mathematical property that GCD(a,b) = GCD(b, a mod b). It continues until one number becomes zero, at which point the other number is the GCD.

Key Points

  • Time complexity: O(log min(a,b))
  • Space complexity: O(log min(a,b)) for recursive, O(1) for iterative
  • Works efficiently even for large numbers
  • The iterative version is more space-efficient

Conclusion

The Euclidean algorithm is one of the most efficient methods to find GCD of two numbers. Both recursive and iterative implementations work well, with the iterative version being more memory-efficient for large inputs.

Updated on: 2026-03-15T10:55:35+05:30

379 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements