c语言请编写函数,求两个整数的最小公倍数。 函数接口定义: int Lcm(int x, int y); 说明:参数 x 和 y 是两个任意整数(包括正整数、零和负整数),函数值为最小公倍数。 要求:规定最小公倍数为非负整数。当 x 和 y 中有一个为 0 时,最小公倍数规定为 0。当其中有负数时,先进行绝对值,后再求最小公倍数
时间: 2024-02-22 18:57:49 浏览: 48
以下是求两个整数最小公倍数的 C 语言函数实现:
```c
int gcd(int a, int b) // 计算 a 和 b 的最大公约数
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
int Lcm(int x, int y) // 求最小公倍数
{
if (x == 0 || y == 0)
return 0;
x = abs(x);
y = abs(y);
return (x * y) / gcd(x, y);
}
```
函数中用到了辗转相除法求最大公约数,然后用两数之积除以最大公约数得到最小公倍数。需要注意的是,当有一个数为 0 时,最小公倍数为 0,当有负数时,需要先取绝对值再求最小公倍数。
相关问题
c语言编写函数求两个整数的最小公倍数。
```c
#include <stdio.h>
int gcd(int a, int b); // 求最大公约数
int lcm(int a, int b); // 求最小公倍数
int main()
{
int num1, num2;
printf("请输入两个整数:");
scanf("%d %d", &num1, &num2);
printf("%d 和 %d 的最小公倍数是:%d\n", num1, num2, lcm(num1, num2));
return 0;
}
int gcd(int a, int b)
{
int temp;
while (b != 0)
{
temp = a % b;
a = b;
b = temp;
}
return a;
}
int lcm(int a, int b)
{
return a * b / gcd(a, b);
}
```
请编写函数,求两个整数的最小公倍数。c语言
以下是求两个整数的最小公倍数的C语言代码:
```c
#include <stdio.h>
int gcd(int a, int b); // 求最大公约数的函数
int lcm(int a, int b) {
return a * b / gcd(a, b); // 最小公倍数等于两数之积除以最大公约数
}
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b); // 辗转相除法求最大公约数
}
int main() {
int a, b;
printf("请输入两个整数:\n");
scanf("%d %d", &a, &b);
printf("它们的最小公倍数为:%d", lcm(a, b));
return 0;
}
```
其中,`gcd`函数用辗转相除法求最大公约数,`lcm`函数用两数之积除以最大公约数求最小公倍数。在`main`函数中,先输入两个整数,然后调用`lcm`函数求它们的最小公倍数,最后输出结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)