NumPy GCD Greatest Common Divisor

🔢 NumPy GCD (Greatest Common Divisor)

NumPy provides a vectorized function np.gcd() to compute the greatest common divisor of integers element-wise.


✅ 1. Basic GCD of Two Numbers

import numpy as np

a = 12
b = 15

gcd = np.gcd(a, b)
print(gcd) # 3

  • GCD of 12 and 15 is 3 → largest number that divides both


✅ 2. GCD of Arrays

arr1 = np.array([8, 12, 20])
arr2 = np.array([12, 15, 30])

gcd_arr = np.gcd(arr1, arr2)
print(gcd_arr) # [4 3 10]

  • Computes element-wise GCD

  • gcd_arr[i] = GCD(arr1[i], arr2[i])


✅ 3. GCD with Scalars and Arrays

arr = np.array([14, 28, 35])
scalar = 7

gcd_arr = np.gcd(arr, scalar)
print(gcd_arr) # [7 7 7]

  • Scalar is broadcasted to array automatically


✅ 4. GCD of Multiple Numbers

  • NumPy gcd is element-wise. To find GCD of multiple numbers, use reduce:

arr = np.array([12, 18, 24])
overall_gcd = np.gcd.reduce(arr)
print(overall_gcd) # 6
  • Computes GCD of all elements in the array


✅ 5. Notes & Tips

  • GCD is always ≤ min(a, b)

  • Useful in fractions simplification, ratio calculations, and number theory problems

  • Works with integers only


🎯 Practice Exercises

  1. Find the GCD of 36 and 60.

  2. Find element-wise GCD of arrays [12, 18, 24] and [6, 9, 12].

  3. Find the GCD of [8, 12, 16, 20] using np.gcd.reduce().

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *