c-plus-plus
  1. c-plus-plus-find-the-gcd-of-two-numbers

C++ Program - Find the GCD of Two Numbers

Syntax

int gcd(int num1, int num2) {
    if (num1 == 0)
        return num2;
    return gcd(num2 % num1, num1);
}

Example

#include <iostream>
using namespace std;

int gcd(int num1, int num2) {
    if (num1 == 0)
        return num2;
    return gcd(num2 % num1, num1);
}

int main() {
    int num1 = 14;
    int num2 = 28;
    int result = gcd(num1, num2);
    cout << "The GCD of " << num1 << " and " << num2 << " is " << result << endl;
    return 0;
}

Output

The GCD of 14 and 28 is 14

Explanation

In the above example, we have defined a function called "gcd" which takes two arguments (num1 and num2) and recursively finds the GCD (Greatest Common Divisor) of two numbers.

Use

Finding the GCD of two numbers is an important mathematical problem and has several real-world applications. This program can be used in any application that requires finding the GCD of two numbers.

Important Points

  • GCD (Greatest Common Divisor) is the largest positive integer that divides both numbers without leaving a remainder.
  • Euclid's algorithm is a common way to find the GCD of two numbers.
  • In the above example, we have used recursion to implement Euclid's algorithm.

Summary

In summary, the above C++ program demonstrates how to find the GCD of two numbers using Euclid's algorithm. The program is simple and easy to understand and can be used in any application that requires finding the GCD of two numbers.

Published on: