I am trying to write a function to find the gcd of 2 numbers, using Euclid's Algorithm which I found here.
From the larger number, subtract the smaller number as many times as you can until you have a number that is smaller than the small number. (or without getting a negative answer) Now, using the original small number and the result, a smaller number, repeat the process. Repeat this until the last result is zero, and the GCF is the next-to-last small number result. Also see our Euclid's Algorithm Calculator.
Example: Find the GCF (18, 27)
27 - 18 = 9
18 - 9 = 9
9 - 9 = 0
So, the greatest common factor of 18 and 27 is 9, the smallest result we had before we reached 0.
Following these instructions I wrote a function:
int hcf(int a, int b)
{
int small = (a < b)? a : b;
int big = (a > b)? a : b;
int res;
int gcf;
cout << "small = " << small << "\n";
cout << "big = " << big << "\n";
while ((res = big - small) > small && res > 0) {
cout << "res = " << res << "\n";
}
while ((gcf = small - res) > 0) {
cout << "gcf = " << gcf << "\n";
}
return gcf;
}
However, the second loop seems to be infinite. Can anyone explain why?
I know the website actually shows the code(PHP), but I'm trying to write this code using only the instructions they give.
while ((res = big - small) > small && res > 0). If you just look at this, it is not trivial to tell what the value of all your variables will be after the loop is done. That is a very bad thing!int gcd(int a, int b) { return b ? gcd(b, a%b) : a; }instead. Using subtraction just isn't a great idea.