C语言中自定义函数,输入两个正整数,求两个数的最大公约数和最大公倍数
时间: 2024-02-04 08:43:03 浏览: 40
下面是一个求最大公约数和最大公倍数的C函数,可以输入两个正整数,返回它们的最大公约数和最大公倍数:
```c
#include <stdio.h>
int gcd(int a, int b) { // 求最大公约数
if (a % b == 0) {
return b;
} else {
return gcd(b, a % b);
}
}
int lcm(int a, int b) { // 求最大公倍数
return a * b / gcd(a, b);
}
int main() {
int x, y;
printf("请输入两个正整数:");
scanf("%d%d", &x, &y);
printf("%d和%d的最大公约数是%d\n", x, y, gcd(x, y));
printf("%d和%d的最大公倍数是%d\n", x, y, lcm(x, y));
return 0;
}
```
函数`gcd(int a, int b)`用于求最大公约数,实现原理是辗转相除法。函数`lcm(int a, int b)`用于求最大公倍数,实现原理是用两个数的乘积除以它们的最大公约数。
相关问题
用c语言写一个输入两个正整数求出最大公约数和最小公倍数
```c
#include <stdio.h>
int gcd(int a, int b); // 求最大公约数的函数
int lcm(int a, int b); // 求最小公倍数的函数
int main()
{
int a, b;
printf("请输入两个正整数:");
scanf("%d%d", &a, &b);
printf("%d和%d的最大公约数是%d\n", a, b, gcd(a, b));
printf("%d和%d的最小公倍数是%d\n", a, b, lcm(a, b));
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);
}
```
使用辗转相除法求最大公约数,再利用公式 a * b = gcd(a, b) * lcm(a, b) 求最小公倍数。
用c语言写一个输入两个正整数求出最大公约数和最小公倍数不用函数的定义
```c
#include <stdio.h>
int main()
{
int a, b, i, gcd, lcm;
printf("请输入两个正整数:\n");
scanf("%d%d", &a, &b);
// 求最大公约数
for(i = 1; i <= a && i <= b; i++)
{
if(a % i == 0 && b % i == 0)
gcd = i;
}
// 求最小公倍数
lcm = a * b / gcd;
printf("最大公约数为:%d\n", gcd);
printf("最小公倍数为:%d\n", lcm);
return 0;
}
```
运行结果示例:
```
请输入两个正整数:
12 18
最大公约数为:6
最小公倍数为:36
```
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)