c语求最大公因数的算法
时间: 2023-11-25 12:50:15 浏览: 91
以下是C语言求最大公因数的两种算法:
1.辗转相除法
```c
#include <stdio.h>
int gcd(int a, int b) {
int temp;
while (b != 0) {
temp = a % b;
a = b;
b = temp;
}
return a;
}
int main() {
int a = 12, b = 18;
printf("The gcd of %d and %d is %d\n", a, b, gcd(a, b)); // 输出:The gcd of 12 and 18 is 6
return 0;
}
```
2.质因数分解法
```c
#include <stdio.h>
int gcd(int a, int b) {
int i, gcd = 1;
for (i = 2; i <= a && i <= b; i++) {
while (a % i == 0 && b % i == 0) {
gcd *= i;
a /= i;
b /= i;
}
}
return gcd;
}
int main() {
int a = 12, b = 18;
printf("The gcd of %d and %d is %d\n", a, b, gcd(a, b)); // 输出:The gcd of 12 and 18 is 6
return 0;
}
```
阅读全文