c语言分别求2个整数的最大公约数和最小公倍数
时间: 2024-06-13 15:09:06 浏览: 13
以下是C语言分别求两个整数的最大公约数和最小公倍数的代码:
```c
#include <stdio.h>
// 求最大公约数
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
// 求最小公倍数
int lcm(int a, int b) {
return a * b / gcd(a, b);
}
int main() {
int num1, num2;
printf("请输入两个整数:\n");
scanf("%d %d", &num1, &num2);
printf("%d和%d的最大公约数为:%d\n", num1, num2, gcd(num1, num2));
printf("%d和%d的最小公倍数为:%d\n", num1, num2, lcm(num1, num2));
return 0;
}
```
相关问题
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 a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
// 求两个整数的最小公倍数
int lcm(int a, int b) {
return a * b / gcd(a, b);
}
int main() {
int a, b;
printf("请输入两个整数:");
scanf("%d%d", &a, &b);
printf("它们的最大公约数为:%d\n", gcd(a, b));
printf("它们的最小公倍数为:%d\n", lcm(a, b));
return 0;
}
```
相关推荐
![](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)