Skip to content

Instantly share code, notes, and snippets.

@juanfal
Created November 1, 2025 12:46
Show Gist options
  • Select an option

  • Save juanfal/e2b01c47405cb83774f2051f4cde712c to your computer and use it in GitHub Desktop.

Select an option

Save juanfal/e2b01c47405cb83774f2051f4cde712c to your computer and use it in GitHub Desktop.
gcd recursive
// gcdr.cpp
// juanfc 2025-11-01
// Recursive solution of gcd
// gcd(a,b) = gcd(b,a) = gcd(a, a-b)
// gcd(a, 0) = a
// https://en.wikipedia.org/wiki/Euclidean_algorithm
//
#include <iostream>
using namespace std;
int main()
{
int gcd(int, int);
int a, b;
do {
cout << "Input a and b (0 0 ends): ";
cin >> a >> b;
cout << "gcd(" << a << "," << b << "): " << gcd(a, b) << endl;
} while (a != 0 and b != 0);
return 0;
}
int gcd(int a, int b)
{
// if you want to see the process
// cout << "-- " << a << " - " << b << endl;
if (b == 0)
return a;
else
return gcd(b, a % b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment