问题
I am trying to find the GCD of two numbers using Euclid's algorithm in C (recursively) and I do know that mathematically it's not completely perfect yet as it neglects negative number conditions, but I just want this one to work for positive numbers for now.
#include <stdio.h>
int gcd(int m, int n);
int main() {
return gcd(60, 24);
}
int gcd(int m, int n) {
if (m < n) {
//swapping both a and b
m = m + n;
n = m - n;
m = m - n;
}
if (m == n) {
return m;
} else {
return gcd(n, m % n);
}
}
回答1:
gcd(60, 24)
-> gcd(24, 12)
-> gcd(12, 0)
.
That means you need to add a check.
if ( n == 0 )
{
return m;
}
or
if ( m%n == 0 )
{
return n;
}
You can also remove the variable swapping code with another call to the function with the values swapped in the call.
int gcd(int m, int n) {
if (m < n) {
return gcd(n, m);
}
if (m%n == 0) {
return n;
} else {
return gcd(n, m % n);
}
}
回答2:
The code for a recursive GCD looks like this
int gcd(int m, int n)
{
if (n==0)
return m;
return gcd(n, m % n);
}
There is no need to swap arguments, since that will be taken care of by the recursion. For example, consider gcd(24, 60)
. In this case n=60
and m % n = 24%60 = 24
. So the recursive call is gcd(60,24)
, swapping the arguments automatically.
来源:https://stackoverflow.com/questions/35095965/why-is-my-gcd-program-in-c-not-running