C++ Program to Find GCD

Updated on December 17, 2024
Find gcd header image

Introduction

The greatest common divisor (GCD) of two or more integers, which are not all zero, is the largest positive integer that divides each of the integers without any remainder. In mathematics and computer programming, finding the GCD of two numbers is a fundamental concept; particularly in fields like number theory and for solving problems requiring simplification of fractions. The Euclidean algorithm, which is based on the principle of recursive subtraction, is most commonly used for this purpose in programming.

In this article, you will learn how to efficiently compute the GCD of two numbers using C++. Explore how to implement the traditional Euclidean algorithm, as well as its more efficient version using modulo operation. Additionally, see how to extend the basic algorithm to handle multiple numbers.

Basic GCD Calculation with Subtraction

Implementing the Euclidean Algorithm Using Subtraction

  1. Introduce two numbers, and repeatedly subtract the smaller one from the larger one.

  2. Continue this process until the two numbers become equal; that number will be the GCD.

    cpp
    #include <iostream>
    using namespace std;
    
    int gcdSubtraction(int a, int b) {
        while (a != b) {
            if (a > b) {
                a -= b;
            } else {
                b -= a;
            }
        }
        return a;
    }
    
    int main() {
        cout << "GCD of 56 and 98 is " << gcdSubtraction(56, 98) << endl;
        return 0;
    }
    

    In this code, two integers a and b are repeatedly modified by subtracting the smaller from the larger until they are equal. At that point, either number can be returned as the GCD.

Running the program

Execute the program, and observe the output which should state that the GCD of 56 and 98 is 14.

Efficient GCD Calculation with Modulo

Using the Euclidean Algorithm with the Modulo Operation

  1. Modify the conventional algorithm by using the modulo operation instead of subtraction; this improves efficiency by reducing iterations.

  2. Continue with the modulo operation until one of the numbers becomes zero.

    cpp
    #include <iostream>
    using namespace std;
    
    int gcdModulo(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
    
    int main() {
        cout << "GCD of 54 and 24 is " << gcdModulo(54, 24) << endl;
        return 0;
    }
    

    This implementation uses the modulo operator to reduce the larger number significantly at each step, speeding up the convergence on the GCD. The operation a % b keeps going until b becomes zero, at which point a is the GCD.

Understanding the code behavior

When you run this segment, it returns a result quickly, showing the GCD of 54 and 24 as 6.

Extending to Multiple Numbers

Calculating GCD of Several Numbers

  1. Iterate through an array of numbers, using the GCD function on each pair iteratively to find the overall GCD.

  2. Leverage the fact that the GCD of several numbers can be computed pairwise.

    cpp
    #include <iostream>
    using namespace std;
    
    int gcdModulo(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
    
    int gcdMultiple(int arr[], int n) {
        int result = arr[0];
        for (int i = 1; i < n; i++) {
            result = gcdModulo(result, arr[i]);
        }
        return result;
    }
    
    int main() {
        int arr[] = {36, 60, 24, 96};
        int n = sizeof(arr) / sizeof(arr[0]);
        cout << "GCD of the array is " << gcdMultiple(arr, n) << endl;
        return 0;
    }
    

    This code defines an array and calculates its GCD by reducing pairs of elements using the previously defined gcdModulo function. The result remains efficient and easy to comprehend.

Conclusion

The ability to compute the GCD of integers efficiently is an invaluable skill in C++. By making use of algorithms like those illustrated, you improve your ability to handle arithmetic operations, optimize performance, and simplify more complex mathematical problems effectively. Implement these strategies in various situations to ensure your code remains robust, efficient, and adaptable.