Open In App

numpy.gcd() in Python

Last Updated : 12 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

numpy.gcd() function computes the greatest common divisor (GCD) of two integers element-wise. The GCD of two numbers is the largest positive integer that divides both numbers without leaving a remainder.

Python
import numpy as np
res = np.gcd(36, 60)
print(res)

Output
12

The GCD of 36 and 60 is 12, which is the largest number that divides both without leaving a remainder.

Syntax

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

Parameters:

ParameterTypeDescription
x1array_likeFirst input array or integer
x2array_likeSecond input array or integer
outndarray, optionalOptional output array to store result
wherebool or array_like, optionalCondition array specifying where to compute
casting{'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optionalControls data casting (default: 'same_kind')
order{'C', 'F', 'A', 'K'}, optionalMemory layout order of result (default: 'K')
dtypedata-type, optionalOverrides calculation data type
subokbool, optionalPreserve subclasses if True
signaturecallable, optionalInternal use for generalized ufuncs
extobjobject, optionalInternal error handling

Returns: This function returns the element-wise greatest common divisor of x1 and x2.

Examples

Example 1: GCD Element-wise on arrays

Python
import numpy as np

a = np.array([24, 36, 48])
b = np.array([18, 60, 72])
res = np.gcd(a, b)
print(res)

Output
[ 6 12 24]

This function computes the GCD for each corresponding pair of elements in a and b.

  • GCD(24, 18) is 6
  • GCD(36, 60) is 12
  • GCD(48, 72) is 24

Example 2: GCD of an array and a scalar

Python
import numpy as np

a = np.array([20, 30, 40])
res = np.gcd(a, 10)
print(res)

Output
[10 10 10]

The scalar 10 is broadcast across all elements in the array a. The GCD of 10 with each number in a is computed.

Example 3: GCD with negative numbers

Python
import numpy as np

a = np.array([-20, -30, -40])
b = np.array([15, 25, 35])
res = np.gcd(a, b)
print(res)

Output
[5 5 5]

This function works with negative integers too and it returns the positive GCD value, as the GCD is always positive by definition.

  • GCD(-20, 15) is 5
  • GCD(-30, 25) is 5
  • GCD(-40, 35) is 5

Next Article

Similar Reads