Return the greatest common divisor and lowest common multiple in Numpy

NumpyServer Side ProgrammingProgramming

To return 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).

To return the lowest common multiple, use the numpy.lcm() method in Python Numpy. The greatest common divisor of the absolute value of the inputs This is a scalar if both x1 and x2 are scalars.

Steps

At first, import the required library −

import numpy as np

To return 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...\n", np.lcm(15, 30))
print("LCM...\n", np.lcm(10, 50))
print("LCM...\n", np.lcm.reduce([6, 18, 30]))

To return the lowest common multiple, use the numpy.lcm() method in Python Numpy −

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

Example

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...\n", np.lcm(15, 30))
print("LCM...\n", np.lcm(10, 50))
print("LCM...\n", np.lcm.reduce([6, 18, 30]))

# To returns the lowest common multiple, use the numpy.lcm() method in Python Numpy
print("GCD...\n", np.gcd(15, 30))
print("GCD...\n", np.gcd(10, 50))
print("GCD...\n", np.gcd.reduce([25, 75, 100, 125]))

Output

LCM...
30
LCM...
50
LCM...
90
GCD...
15
GCD...
10
GCD...
25
raja
Updated on 08-Feb-2022 10:18:36

Advertisements