pythonarraysnumpygreatest-common-divisor

Numpy.gcd using more than 2 arrays


I am wondering if it is possible to compute the greatest common divisor for more than 2 arrays using numpy.gcd(). Using the following arrays for x, y, z:

import numpy as np
x = np.array([[4,6,28],[2,5,6]])
y = np.array([[2,1,7],[7,23,6]])
z = np.array([[3,0,4],[7,4,3]])

Here the gcd code taking the 3 arrays:

result = np.gcd(x,y,z)

Which leads to:

array([[2, 1, 7],
   [1, 1, 6]])

result[0,2]

7

Instead of 7 shouldn't this be 1? Given the numbers 28, 7, 4, the following returns 1.

numpy.gcd.reduce([28, 7, 4])

So my question is if I am making a mistake at some point, or is numpy.gcd not capable of taking as input 3 arrays and simply computing the gcd over the first two arrays it receives as input?


Solution

  • From https://numpy.org/doc/stable/reference/generated/numpy.gcd.html

    The function signature is this:

    def numpy.gcd(x1, x2, /, out=None, *, ...):
    

    If you call gcd with three arguments, you are basically doing z = gcd(x, y). Therefore you need to come up with your own function. It could be something like

    def my_gcd(x, y, z):
        return np.gcd(np.gcd(x, y), z)
    

    which would return

    [[1 1 1]
     [1 1 3]]