C语言求m和n的最大公约数和最小公倍数,加上注释
时间: 2024-04-29 16:25:21 浏览: 10
好的,这是一个关于C语言求最大公约数和最小公倍数的代码,已经加上注释:
```c
#include <stdio.h>
// 定义一个函数,用于求最大公约数
int gcd(int a, int b) {
// 如果b为0,则a即为最大公约数
if (b == 0) {
return a;
}
// 否则,递归求b和a%b的最大公约数
else {
return gcd(b, a % b);
}
}
// 定义一个函数,用于求最小公倍数
int lcm(int a, int b) {
// 公式:最小公倍数 = 两数之积 ÷ 最大公约数
return a * b / gcd(a, b);
}
int main() {
int m, n, result_gcd, result_lcm;
printf("请输入两个正整数m和n:");
scanf("%d %d", &m, &n);
result_gcd = gcd(m, n);
result_lcm = lcm(m, n);
printf("%d和%d的最大公约数为%d,最小公倍数为%d\n", m, n, result_gcd, result_lcm);
return 0;
}
```
希望可以帮到您!接下来,您还有其他问题吗?
相关问题
c语言求m和n最大公约数
以下是用C语言求m和n最大公约数的代码:
```c
#include <stdio.h>
int main() {
int m, n, t, r;
printf("请输入两个数:\n");
scanf("%d%d", &m, &n);
if (m < n) {
t = m;
m = n;
n = t;
}
while (n != 0) {
r = m % n;
m = n;
n = r;
}
printf("最大公约数为:%d\n", m);
return 0;
}
```
输入m,n求最大公约数和最小公倍数c语言
以下是求最大公约数和最小公倍数的C语言代码:
```c
#include <stdio.h>
int main()
{
int m, n, i, gcd, lcm;
printf("Enter two positive integers: ");
scanf("%d %d", &m, &n);
// 求最大公约数
for(i=1; i<=m && i<=n; ++i)
{
if(m%i==0 && n%i==0)
gcd = i;
}
// 求最小公倍数
lcm = m*n/gcd;
printf("Greatest common divisor of %d and %d is %d\n", m, n, gcd);
printf("Least common multiple of %d and %d is %d\n", m, n, lcm);
return 0;
}
```
运行结果:
```
Enter two positive integers: 12 30
Greatest common divisor of 12 and 30 is 6
Least common multiple of 12 and 30 is 60
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)