输入两个正整数,求最大公约数和最小公倍数c语言
时间: 2023-11-22 20:04:49 浏览: 151
这个问题可以用两种方法来解决。第一种方法是使用全局变量,将最大公约数和最小公倍数设为全局变量,在主函数中输出它们的值。第二种方法是不使用全局变量,最大公约数和最小公倍数由被调模块返回值。具体思路如下:
方法一:
```c
#include <stdio.h>
int gcd, lcm; // 全局变量
int GCD(int x, int y) { // 求最大公约数
int r;
while (y > 0) {
r = x % y;
x = y;
y = r;
}
return x;
}
int LCM(int x, int y) { // 求最小公倍数
gcd = GCD(x, y);
lcm = x * y / gcd; return lcm;
}
int main() {
int x, y;
printf("请输入两个正整数:");
scanf("%d %d", &x, &y);
LCM(x, y);
printf("最大公约数为:%d\n", gcd);
printf("最小公倍数为:%d\n", lcm);
return 0;
}
```
方法二:
```c
#include <stdio.h>
int GCD(int x, int y) { // 求最大公约数
int r;
while (y > 0) {
r = x % y;
x = y;
y = r;
}
return x;
}
int LCM(int x, int y) { // 求最小公倍数
int gcd = GCD(x, y);
int lcm = x * y / gcd;
return lcm;
}
int main() {
int x, y, gcd, lcm;
printf("请输入两个正整数:");
scanf("%d %d", &x, &y);
gcd = GCD(x, y);
lcm = LCM(x, y);
printf("最大公约数为:%d\n", gcd);
printf("最小公倍数为:%d\n", lcm);
return 0;
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)