以下程序用辗转相除法求出两个正整数的最大公约数和最小公倍数
时间: 2023-12-30 15:50:16 浏览: 35
```python
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
def lcm(a, b):
return a * b // gcd(a, b)
a = int(input())
b = int(input())
print("最大公约数为:", gcd(a, b))
print("最小公倍数为:", lcm(a, b))
```
其中,`gcd`函数用于求最大公约数,`lcm`函数用于求最小公倍数。程序输入两个正整数`a`和`b`,输出它们的最大公约数和最小公倍数。
相关问题
c语言用辗转相除法求出两个正整数的最大公约数和最小公倍数
最大公约数和最小公倍数的求法如下:
最大公约数(GCD):辗转相除法,也叫欧几里得算法,是求两个正整数的最大公约数的常用方法。
最小公倍数(LCM):两个正整数a和b的积等于它们的最大公约数(GCD)和最小公倍数(LCM)的积,即a*b=GCD(a,b)*LCM(a,b),因此可以通过最大公约数来求最小公倍数。
以下是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("Enter two positive integers: ");
scanf("%d %d", &num1, &num2);
printf("GCD(%d, %d) = %d\n", num1, num2, gcd(num1, num2));
printf("LCM(%d, %d) = %d\n", num1, num2, lcm(num1, num2));
return 0;
}
```
代码解释:
- 定义函数gcd来求最大公约数,使用递归实现辗转相除法,当b为0时,a即为最大公约数。
- 定义函数lcm来求最小公倍数,使用a*b/GCD(a,b)的公式来计算。
- 在main函数中,先输入两个正整数,然后调用gcd和lcm函数分别求出它们的最大公约数和最小公倍数,并输出结果。
c语言循环结构用辗转相除法求出两个正整数的最大公约数和最小公倍数
最大公约数:
```c
#include <stdio.h>
int main() {
int num1, num2, remainder, gcd;
printf("请输入两个正整数:\n");
scanf("%d %d", &num1, &num2);
while(num2 != 0) {
remainder = num1 % num2;
num1 = num2;
num2 = remainder;
}
gcd = num1;
printf("最大公约数为:%d\n", gcd);
return 0;
}
```
最小公倍数:
```c
#include <stdio.h>
int main() {
int num1, num2, remainder, gcd, lcm;
printf("请输入两个正整数:\n");
scanf("%d %d", &num1, &num2);
int temp1 = num1, temp2 = num2;
while(num2 != 0) {
remainder = num1 % num2;
num1 = num2;
num2 = remainder;
}
gcd = num1;
lcm = temp1 * temp2 / gcd;
printf("最小公倍数为:%d\n", lcm);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.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)