溫馨提示×

C語言實(shí)現(xiàn)求最大公約數(shù)的三種方法

小云
154
2023-08-11 14:06:26
欄目: 編程語言

方法一:暴力枚舉法

#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("請輸入兩個數(shù):");
scanf("%d %d", &a, &b);
printf("最大公約數(shù)為:%d\n", gcd(a, b));
return 0;
}

方法二:輾轉(zhuǎn)相除法

#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("請輸入兩個數(shù):");
scanf("%d %d", &a, &b);
printf("最大公約數(shù)為:%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("請輸入兩個數(shù):");
scanf("%d %d", &a, &b);
printf("最大公約數(shù)為:%d\n", gcd(a, b));
return 0;
}

0