Does numpy
have a gcd
function somewhere in its structure of modules?
I\'m aware of fractions.gcd
but thought a numpy
In case the desired result is not an element-wise gcd but rather the gcd of all numbers in the array, you may use the code below.
import numpy as np
from math import gcd as mathgcd
def numpy_set_gcd(a):
a = np.unique(a)
if not a.dtype == np.int or a[0] <= 0:
raise ValueError("Argument must be an array of positive " +
"integers.")
gcd = a[0]
for i in a[1:]:
gcd = mathgcd(i, gcd)
if gcd == 1:
return 1
return gcd
Depending on the use case, it can be faster to omit the sorting step a = np.unique(a)
.
An alternative (maybe more elegant but slower) implementation using ufuncs is
import numpy as np
from math import gcd as mathgcd
npmathgcd = np.frompyfunc(mathgcd, 2, 1)
def numpy_set_gcd2(a):
a = np.unique(a)
if not a.dtype == np.int or a[0] <= 0:
raise ValueError("Argument must be an array of positive " +
"integers.")
npmathgcd.at(a[1:], np.arange(a.size-1), a[:-1])
return a[-1]