Return the greatest common divisor and lowest common multiple in Numpy


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

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

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...
", 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]))

Output

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

Updated on: 08-Feb-2022

302 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements