NumPy ufunc for Finding GCD (Greatest Common Divisor)

Last updated 1 month, 3 weeks ago | 126 views 75     5

Tags:- Python NumPy

The Greatest Common Divisor (GCD) is an essential operation in mathematics and computer science. It finds the largest number that divides two integers without leaving a remainder. NumPy provides a fast and vectorized method to compute GCDs using its universal functions (ufuncs).

This article covers np.gcd, introduced in NumPy 1.17, including its extended methods: reduce, accumulate, and outer, for powerful array-wide operations.


What is GCD?

The GCD (or HCF) of two integers is the largest number that divides both without leaving a remainder.

Examples:

  • GCD(8, 12) = 4

  • GCD(100, 75) = 25

In mathematics:

GCD(a,b)=max(x) such that x∣a and x∣b\text{GCD}(a, b) = \text{max}(x) \text{ such that } x \mid a \text{ and } x \mid b


NumPy's np.gcd Function

The NumPy ufunc:

np.gcd(x1, x2)

computes the element-wise GCD of two arrays (or scalars).

⚠️ Prerequisites:

  • Available in NumPy 1.17.0+

  • Works only with integers


np.gcd – Main Variants

Method Purpose
np.gcd(x1, x2) Element-wise GCD
np.gcd.reduce(arr) GCD across an array
np.gcd.accumulate(arr) Stepwise cumulative GCD
np.gcd.outer(x1, x2) All pairwise GCD combinations

Step-by-Step Examples


1. np.gcd(x1, x2) – Element-wise GCD

✅ Example:

import numpy as np

a = np.array([12, 18, 100])
b = np.array([8, 24, 75])

result = np.gcd(a, b)
print(result)

Output:

[4 6 25]

Explanation:

  • GCD(12, 8) = 4

  • GCD(18, 24) = 6

  • GCD(100, 75) = 25


2. np.gcd.reduce() – Reduce an Array to One GCD

✅ Example:

arr = np.array([60, 48, 36])
result = np.gcd.reduce(arr)
print(result)

Output:

12

Explanation:
GCD(60, 48) = 12, then GCD(12, 36) = 12.


3. np.gcd.accumulate() – Step-by-Step GCDs

✅ Example:

arr = np.array([60, 48, 36])
result = np.gcd.accumulate(arr)
print(result)

Output:

[60 12 12]

Explanation:

  • Step 1: 60

  • Step 2: GCD(60, 48) = 12

  • Step 3: GCD(12, 36) = 12


4. np.gcd.outer() – Outer Pairwise GCD Matrix

✅ Example:

a = np.array([12, 18])
b = np.array([8, 24, 36])

result = np.gcd.outer(a, b)
print(result)

Output:

[[4 12 12]
 [2  6 18]]

Explanation:
Each element of a is paired with each element of b to compute GCDs.


✅ Full Working Example

import numpy as np

a = np.array([60, 48, 36])
b = np.array([20, 16, 12])

# Element-wise GCD
print("Element-wise GCD:")
print(np.gcd(a, b))  # [20 16 12]

# Reduce: GCD of all elements
print("\nGCD of entire array:")
print(np.gcd.reduce(a))  # 12

# Accumulate: GCD step-by-step
print("\nCumulative GCD:")
print(np.gcd.accumulate(a))  # [60 12 12]

# Outer GCD matrix
print("\nOuter GCD matrix:")
print(np.gcd.outer(a, b))

Tips and Best Practices

✅ Useful Tips

  • Use np.gcd.reduce() to find a single GCD across a list of numbers.

  • Use np.gcd.accumulate() to track how GCD evolves across a sequence.

  • Use outer() when generating GCD matrices, useful for teaching, cryptography, or numerical simulations.


⚠️ Common Pitfalls

  1. Requires Integers Only
    np.gcd(12.0, 8.0)TypeError
    np.gcd(12, 8)

  2. Negative Inputs
    GCD is always non-negative. Negative values are treated as absolute.

    np.gcd(-12, 8)  # Output: 4
    
  3. Zeros in Input
    GCD with zero:

    • GCD(a, 0) = |a|

    • GCD(0, 0) = 0

    np.gcd(0, 25)  # 25
    np.gcd(0, 0)   # 0
    
  4. Version Compatibility
    Works only in NumPy 1.17+. Check version:

    import numpy as np
    print(np.__version__)
    

Summary Table

Function Description Output Shape
np.gcd(x, y) Element-wise GCD Broadcasted shape
np.gcd.reduce(array) One GCD from entire array Scalar
np.gcd.accumulate() Step-by-step cumulative GCD Same shape
np.gcd.outer(a, b) Matrix of all pairwise GCDs 2D matrix

Use Cases

  • Cryptography: Fundamental to RSA and modular inverses.

  • Fractions & Simplification: Reduce ratios to simplest form.

  • Scheduling/LCM calculations: Used in computing LCM via:

    LCM(a,b)=a⋅bGCD(a,b)\text{LCM}(a, b) = \frac{a \cdot b}{\text{GCD}(a, b)}
  • Number Theory: Euclidean algorithm, coprime checks.


Conclusion

NumPy’s np.gcd and its ufunc extensions offer a fast, flexible, and memory-efficient way to calculate GCDs on arrays. Whether you’re simplifying fractions, working with modular arithmetic, or teaching number theory, mastering np.gcd will make your code cleaner and significantly faster.