Loading [MathJax]/jax/output/HTML-CSS/jax.js

在 NumPy 中返回最大公约数和最小公倍数


如需返回最大公约数,请在 Python Numpy 中使用 numpy.gcd() 方法。参数是数值数组。如果 x1.shape != x2.shape,它们必须可广播到通用形状(该形状成为输出的形状)。

如需返回最小公倍数,请在 Python Numpy 中使用 numpy.lcm() 方法。绝对值输入的最大公约数,如果 x1 和 x2 都是标量,则这是一个标量。

步骤

首先,导入所需的库 −

import numpy as np

如需返回最大公约数,请在 Python Numpy 中使用 numpy.gcd() 方法。参数是数值数组。如果 x1.shape != x2.shape,它们必须可广播到通用形状(该形状成为输出的形状) −

print("LCM...", np.lcm(15, 30)) print("LCM...", np.lcm(10, 50)) print("LCM...", np.lcm.reduce([6, 18, 30]))

如需返回最小公倍数,请在 Python Numpy 中使用 numpy.lcm() 方法 −

print("GCD...", np.gcd(15, 30)) print("GCD...", np.gcd(10, 50)) print("GCD...", np.gcd.reduce([25, 75, 100, 125]))

示例

Open Compiler
import numpy as np # To returns the greatest common divisor, use the numpy.gcd() method in Python Numpy # The parameters are arrays of values. # If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output). print("LCM...", np.lcm(15, 30)) print("LCM...", np.lcm(10, 50)) print("LCM...", np.lcm.reduce([6, 18, 30])) # To returns the lowest common multiple, use the numpy.lcm() method in Python Numpy print("GCD...", np.gcd(15, 30)) print("GCD...", np.gcd(10, 50)) print("GCD...", np.gcd.reduce([25, 75, 100, 125]))

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

LCM...
30
LCM...
50
LCM...
90
GCD...
15
GCD...
10
GCD...
25

更新于: 08-Feb-2022

362 次浏览

启动你的 职业

完成课程以获得认证

开始
广告