两个整数的最大公约数(C语言程序设计现代方法第二版第六章6.2)
/*
- 辗转相除法
辗转相除法
如果b等于0,计算结束,a就是最大公约数;
否则,计算a除以b的余数,让a等于b,而b等于那个余数;
回到第一步。
a b t
12 18 12
18 12 6
12 6 0
6 0
*/
#include <stdio.h>
int main()
{
int a,b,t;
scanf("%d %d", &a,&b);
while (b!=0){
t=a % b;
a=b;
b=t;
}
printf("%d\n",a);
return 0;
}
- 枚举法
枚举法
#include <stdio.h>
int main()
{
int a,b,min,i=1,gcd;
scanf("%d / %d", &a, &b);
if(a>b){
min=a;
}else{
min=b;
}
while (i<min){
if(a%i== 0){
if(b%i== 0){
gcd=i;
}
}i++;
}//当然可以把while改写为for语句
printf("gcd=%d\n",gcd)