辗转相除法求最大公约数。 如果b等于0,计算结束,a就是最大公约数; 否则,计算a除以b的余数,让a等于b,而b等于那个余数; 回到第一步。 例如: a b 余数 15 20 15 20 15 5 15 5 0 5 0
#include <stdio.h>
int main() {
int a,b;
int remainder=0; //初始化一个余数
printf("Please enter a and b:\n");
scanf("%d %d",&a,&b);
while (b>=0) {
if (b == 0) {
printf("greatest common divisor is %d", a);
break; //防止形成死循环
} else {
remainder = a % b;
a = b;
b = remainder;
}
}
return 0;
}