Print the gcd of two integers - C++ Data Structure

C++ examples for Data Structure:Algorithm

Introduction

The greatest common divisor (GCD) of two integers is the largest integer that evenly divides each of the numbers.

Demo Code

#include <iostream>

int gcd(int, int);

int main(int argc, const char *argv[]) {
    int num1, num2;

    std::cout << "Enter two integers: ";
    std::cin >> num1 >> num2;

    std::cout << "Greatest Common Divisor: " << gcd(num1, num2) << std::endl;
    return 0;/*  w w  w.  j  av a  2s . c om*/
}
// find and return the greatest common divisor of two integers
int gcd(int x, int y) {
    while (x != y) {
        if (x > y)
            x -= y;
        else
            y -= x;
    }
    // can return either x or y as both will be the same
    return x;
}

Result


Related Tutorials