C语言求两个整数的最大公约数
时间: 2023-09-23 15:04:44 浏览: 66
可以使用辗转相除法求解两个整数的最大公约数,C语言代码如下:
```c
#include <stdio.h>
int gcd(int a, int b);
int main() {
int a, b;
printf("请输入两个整数:");
scanf("%d %d", &a, &b);
int result = gcd(a, b);
printf("%d和%d的最大公约数是%d\n", a, b, result);
return 0;
}
int gcd(int a, int b) {
int temp;
while (b != 0) {
temp = b;
b = a % b;
a = temp;
}
return a;
}
```
输入两个整数后,程序会调用 `gcd()` 函数计算它们的最大公约数,并输出结果。
相关问题
c语言求两个整数最大公约数和最小公倍数
以下是C语言求两个整数最大公约数和最小公倍数的代码示例:
1. 求最大公约数(辗转相除法)
```c
#include <stdio.h>
int main() {
int a = 0;
int b = 0;
scanf("%d %d", &a, &b);
int m = 0; while (m = a % b) {
a = b;
b = m;
}
printf("最大公约数为:%d\n", b);
return 0;
}
```
2. 求最小公倍数
```c
#include <stdio.h>
int main() {
int a = 0;
int b = 0;
scanf("%d %d", &a, &b);
int m = 0;
// 找出最小值
m = (a > b ? b : a);
// 假设m为最大公约数
while (1) {
if (a % m == 0 && b % m == 0) {
break;
}
m--;
}
printf("最大公约数为:%d\n", m);
printf("最小公倍数为:%d\n", a * b / m);
return 0;
}
```
C语言函数求两个整数最大公约数
以下是一个用C语言函数求两个整数最大公约数的例子:
```c
#include <stdio.h>
int gcd(int x, int y) {
int z = x % y;
while (z) {
x = y;
y = z;
z = x % y;
}
return y;
}
int main() {
int a, b;
scanf("%d %d", &a, &b);
printf("最大公约数为:%d\n", gcd(a, b));
return 0;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)