1.常规法
#include<stdio.h>
#include<stdlib.h>
int main(){
int a, b, i,j;
printf("请输入两个数\n");
scanf("%d%d", &a, &b);
for (i = 2;i<=a;i++){
if (a%i == 0 && b%i == 0)
{
j = i;
}
}
printf("最大公约数为:%d", j);
system("pause");
return 0;
}
2.辗转相除法
#include<stdio.h>
#include<stdlib.h>
int main() {
int a, b, c;
printf("请输入两个数\n");
scanf("%d%d", &a, &b);
while (b!=0) { //不用比较被除数和除数的大小
c = a % b;
a = b;
b = c;
}
printf("最大公约数为:%d", a);
system("pause");
return 0;
}
3.更相减损法
#include<stdio.h>
int main() {
int i = 0, j = 0, k = 0, a = 0, b = 0;
scanf("%d%d", &i, &j);
for (a = i,b = j;(a % 2 == 0) & (b % 2 == 0);) {
a = a / 2;
b = b / 2;
}
for (k=0;a!=b;) {
while (a > b) {
k = a - b;
a = b;
b = k;
}
if (a == b)
break;
k = b - a;
a = a;
b = k;
}
printf("%d与%d最大公约数为:%d\n",i,j,k);
system("pause");
return 0;
}
转载于:https://blog.51cto.com/14233363/2364136