- 非递归
int gcd(int n, int m){
if(n<m) swap(n,m);
while(m>0){
int t = n%m;
n = m;
m = t;
}
return n;
}
- 递归1
int gcd(int n, int m){
if(n>=m){
if(m==0) return n;
int t = n%m;
n = m;
m = t;
gcd(n,m);
}else{
return gcd(m,n);
}
}
- 递归2
int gcd(int n, int m){
if(n>=m){
if(m==0) return n;
else gcd(m, n%m);
}else{
return gcd(m,n);
}
}
- 递归3
int gcd(int n, int m){
if(m==0) return n;
else return gcd(m,n%m);
}
- 递归4
int gcd(int n, int m){
return m ? gcd(m, n%m) : n;
}
可运行版本:
#include <stdio.h>
int gcd(int n, int m){
return m ? gcd(m, n%m) : n;
}
int main() {
int a, b;
while (~scanf("%d%d", &a, &b)) {
printf("%d\n", gcd(a, b));
}
return 0;
}