方法一:暴力枚舉法
#include <stdio.h>
int gcd(int a, int b) {
int min = (a < b) ? a : b;
int max = (a > b) ? a : b;
for (int i = min; i >= 1; i--) {
if (min % i == 0 && max % i == 0) {
return i;
}
}
return 1;
}
int main() {
int a, b;
printf("請輸入兩個數:");
scanf("%d %d", &a, &b);
printf("最大公約數為:%d\n", gcd(a, b));
return 0;
}
方法二:輾轉相除法
#include <stdio.h>
int gcd(int a, int b) {
while (b != 0) {
int temp = a % b;
a = b;
b = temp;
}
return a;
}
int main() {
int a, b;
printf("請輸入兩個數:");
scanf("%d %d", &a, &b);
printf("最大公約數為:%d\n", gcd(a, b));
return 0;
}
方法三:更相減損法
#include <stdio.h>
int gcd(int a, int b) {
if (a == b) {
return a;
}
int max = (a > b) ? a : b;
int min = (a < b) ? a : b;
return gcd(max - min, min);
}
int main() {
int a, b;
printf("請輸入兩個數:");
scanf("%d %d", &a, &b);
printf("最大公約數為:%d\n", gcd(a, b));
return 0;
}