修正“求最大公约数和最小公倍数”: C经典算法: 欧几里德算法(辗转相除法)
我上次写了个求最大公约数和最小公倍数,后经高手指点,发现其效率很低.所以查询资料,找到了这个c的经典算法,拿出来和和我一样菜的兄弟们分享一下:#include <stdio.h>
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
int main(void) {
int m, n, max, temp;
printf("Please input two numbers:\n");
scanf("%d%d", &n, &m);
if (m < n) {
temp = m;
m = n;
n = temp;
}
max = gcd(m, n);
printf("The max commom divisor is: %d", max);
printf("\n The min common multiple is: %d", m * n / max);
}