Created
November 1, 2025 12:46
-
-
Save juanfal/e2b01c47405cb83774f2051f4cde712c to your computer and use it in GitHub Desktop.
gcd recursive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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