在c语言已用碾转相除法求最大公约数如果还要增加求最小公倍数编写一个程序
时间: 2024-06-10 19:08:29 浏览: 14
好的,这个问题是关于算法的,可以直接回答。
先求出两个数的最大公约数,然后利用以下公式求最小公倍数:
最小公倍数 = (两数的乘积) / 最大公约数
所以,一个求最大公约数和最小公倍数的程序可以像这样:
```c
#include <stdio.h>
int gcd(int a, int b);
int lcm(int a, int b);
int main()
{
int a, b;
printf("请输入两个整数:\n");
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 c;
while (a != 0)
{
c = a;
a = b % a;
b = c;
}
return b;
}
int lcm(int a, int b)
{
return (a * b) / gcd(a, b);
}
```
希望能解答你的问题。
相关问题
用c语言编写代码:用辗转相除法求两个数的最大公约数和最小公倍数
好的,以下是用 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("请输入两个整数: ");
scanf("%d %d", &num1, &num2);
// 计算最大公约数和最小公倍数
printf("最大公约数: %d\n", gcd(num1, num2));
printf("最小公倍数: %d\n", lcm(num1, num2));
return 0;
}
```
希望能对您有所帮助!
编写一个c语言程序,输入两个整数,用辗转相除法计算其最大公约数和最小公倍数。
好的,以下是代码:
```c
#include <stdio.h>
int main() {
int m, n, r, temp1, temp2;
printf("请输入两个整数:\n");
scanf("%d%d", &m, &n);
temp1 = m;
temp2 = n;
while (n != 0) {
r = m % n;
m = n;
n = r;
}
printf("最大公约数为:%d\n", m);
printf("最小公倍数为:%d\n", temp1 * temp2 / m);
return 0;
}
```
以上程序中,我们首先输入两个整数m和n,然后用temp1和temp2保存它们的值,因为在计算最小公倍数时需要用到原始的值。
接下来,我们使用辗转相除法来计算最大公约数。具体来说,我们用r来保存m除以n的余数,然后把n赋值给m,把r赋值给n,直到n等于0为止,此时m就是最大公约数。
最后,我们输出最大公约数和最小公倍数,其中最小公倍数等于temp1和temp2的乘积除以最大公约数。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)