What is numpy.gcd() in Python?

The Greatest Common Divisor (GCD) of two or more numbers is the largest positive number that divides each number. Python’s numpy.gcd() method allows us to calculate the GCD of two numbers or two arrays.

Syntax

numpy.gcd() is declared as follows:

numpy.gcd (x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'gcd'>

In the syntax above, x1 and x2 are non-optional parameters, and the rest are optional.

Parameters

The numpy.gcd() method takes the following compulsory parameters:

  • x1 and x2 [array-like, int] - array of integer values. If the shapesthe shape of an array is the number of elements in each dimension of x1 and x2 are different, they must be broadcastable to a common shape for representing the output.

The numpy.gcd() method takes the following optional parameters:

  • out - represents the location into which the method’s output is stored.

  • where - true value indicates that universal functiona universal function (ufunc) is a function that operates on ndarrays in an element-by-element fashion should be calculated at this position.

  • casting - controls the type of datacasting that should occur. The same_kind option indicates that safe casting or casting within the same kind should take place.

  • order - controls the memory layout order of the output function. The option K means reading the elements in the order they occur in memory.

  • dtype - represents the desired data type of the array.

  • subok - decides if subclasses should be made or not. If true, subclasses will be passed through.

Return value

numpy.gcd() returns the greatest common divisor of the absolute values of the input. The return type is either ndarray or scaler, depending on the input type.

Examples

The examples below show the different ways numpy.gcd() is used in Python.

The GCD of two numbers

The code below outputs the greatest common divisor of two numbers, 10 and 20. The result is shown below:

import numpy as np
a = 10
b = 20
result = np.gcd(a,b)
print(result)

The GCD of an array

To find the GCD of all values in a given array, the reduce() method is used. In the code below, the reduce method utilizes the gcd method on each element of the array and reduces the array by one dimension. The result is shown in the code snippet below:

import numpy as np
arr = np.array([8,32,36])
result = np.gcd.reduce(arr)
print(result)

The GCD of two arrays

numpy.gcd() calculates the greatest common divisor of the elements in the same location of the two arrays and returns an array.

In the example below, the first element of arr1 is 10, and the first element of arr2 is 70. The GCD of 10 and 70 is 10. Hence, the result array has 10 as its first element. This is shown here:

import numpy as np
arr1 = np.array([10,20,35])
arr2 = np.array([70,12,15])
result = np.gcd(arr1,arr2)
print(result)
Copyright ©2024 Educative, Inc. All rights reserved