p ython最小公倍数
时间: 2023-07-11 16:50:15 浏览: 59
你可以使用以下代码来计算两个数的最小公倍数:
```python
def lcm(x, y):
if x > y:
greater = x
else:
greater = y
while True:
if greater % x == 0 and greater % y == 0:
lcm = greater
break
greater += 1
return lcm
num1 = 12
num2 = 20
print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))
```
在这个例子中,我们计算了12和20的最小公倍数,输出结果为60。
相关问题
p ython求最大公约数和最小公倍数
求最大公约数可以使用辗转相除法,也叫欧几里得算法,代码如下:
```python
def gcd(a, b):
while b:
a, b = b, a % b
return a
```
求最小公倍数可以通过最大公约数公式求得,代码如下:
```python
def lcm(a, b):
return a * b // gcd(a, b)
```
其中 `//` 表示整除运算符。
c++ 求最小公倍数
以下是两种C++求最小公倍数的例子:
1.使用辗转相除法求最小公倍数
```c++
#include <iostream>
using namespace std;
int gcd(int a, int b) { // 求最大公约数
return b == 0 ? a : gcd(b, a % b);
}
int lcm(int a, int b) { // 求最小公倍数
return a * b / gcd(a, b);
}
int main() {
int a, b;
cin >> a >> b;
cout << lcm(a, b) << endl;
return 0;
}
```
2.使用结论求最小公倍数
```c++
#include <iostream>
using namespace std;
int gcd(int a, int b) { // 求最大公约数
return b == 0 ? a : gcd(b, a % b);
}
int main() {
int a, b;
cin >> a >> b;
cout << a * b / gcd(a, b) << endl; // 最小公倍数等于两数之积除以最大公约数
return 0;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)