用辗转相除法求最大公约数和最小公倍数,生成C代码
时间: 2024-05-06 11:20:58 浏览: 144
以下是用辗转相除法求解最大公约数和最小公倍数的C代码:
```
#include <stdio.h>
int main() {
int a, b, gcd, lcm, temp;
printf("请输入两个整数:");
scanf("%d %d", &a, &b);
temp = a * b;
while (b != 0) {
int t = b;
b = a % b;
a = t;
}
gcd = a;
lcm = temp / gcd;
printf("最大公约数为:%d\n", gcd);
printf("最小公倍数为:%d\n", lcm);
return 0;
}
```
相关问题
C语言辗转相除法计算最大公约数和最小公倍数
以下是使用C语言辗转相除法计算最大公约数和最小公倍数的示例代码:
```c
#include <stdio.h>
int main() {
int a, b, temp, gcd, lcm;
printf("Enter two positive integers: ");
scanf("%d %d", &a, &b);
// 辗转相除法求最大公约数
int x = a, y = b;
while (y != 0) {
temp = x % y;
x = y;
y = temp;
}
gcd = x;
// 计算最小公倍数
lcm = (a * b) / gcd;
printf("GCD of %d and %d is %d\n", a, b, gcd);
printf("LCM of %d and %d is %d\n", a, b, lcm);
return 0;
}
```
运行结果:
```
Enter two positive integers: 12 18
GCD of 12 and 18 is 6
LCM of 12 and 18 is 36
```
输入两个整数,用辗转相除法计算其最大公约数和最小公倍数编写 c 语言
代码。谢谢!
好的,以下是使用辗转相除法计算两个整数的最大公约数和最小公倍数的 C 语言代码:
#include <stdio.h>
int main() {
int num1, num2, gcd, lcm, remainder, numerator, denominator;
printf("请输入两个整数,以空格分隔:\n");
scanf("%d %d", &num1, &num2);
// 计算最大公约数
numerator = (num1 > num2) ? num1 : num2;
denominator = (num1 > num2) ? num2 : num1;
remainder = numerator % denominator;
while (remainder != 0) {
numerator = denominator;
denominator = remainder;
remainder = numerator % denominator;
}
gcd = denominator;
// 计算最小公倍数
lcm = num1 * num2 / gcd;
printf("最大公约数为:%d\n", gcd);
printf("最小公倍数为:%d\n", lcm);
return 0;
}
希望这个代码可以帮到你!
阅读全文