c语言求最大公约数和最小公倍数的代码
时间: 2024-11-07 16:24:01 浏览: 47
在 C 语言中,求最大公约数 (GCD) 和最小公倍数 (LCM) 的经典算法之一是欧几里得算法 (Euclidean Algorithm) 对于 GCD,以及通过公式 LCM(a, b) = |a * b| / GCD(a, b) 来计算 LCM。以下是 C 语言实现这两个功能的简单示例:
```c
#include <stdio.h>
// 函数声明
int gcd(int a, int b);
int lcm(int a, int b);
// 欧几里得算法求 GCD
int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
// 根据 GCD 计算 LCM
int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
int main() {
int num1, num2;
printf("请输入两个整数:");
scanf("%d %d", &num1, &num2);
int result_gcd = gcd(num1, num2);
int result_lcm = lcm(num1, num2);
printf("两数的最大公约数是:%d\n", result_gcd);
printf("两数的最小公倍数是:%d\n", result_lcm);
return 0;
}
```
在这个例子中,`gcd` 函数递归地计算两个数的最大公约数,而 `lcm` 函数则是基于 `gcd` 的结果来计算最小公倍数。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.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/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)