TExcelTAD
Home › NumPy › ufunc Finding GCD

ufunc Finding GCD

The greatest common divisor (GCD), also called the highest common factor (HCF), of two integers is the largest number that divides both without a remainder. The GCD of 12 and 18 is 6: the divisors of 12 are 1, 2, 3, 4, 6, 12, and the divisors of 18 are 1, 2, 3, 6, 9, 18.

GCD and LCM are partners: for positive integers, gcd(a, b) × lcm(a, b) = a × b.

GCD of two numbers

python · try it yourself
import numpy as np

print(np.gcd(12, 18))
print(np.gcd(17, 5))      # coprime: GCD is 1
print(np.gcd(0, 9))       # gcd with 0 is the other number
print(np.gcd(12, 18) * np.lcm(12, 18), 12 * 18)
6
1
9
216 216

Element-wise GCD of arrays

python · try it yourself
import numpy as np

a = np.array([20, 21, 36, 100])
b = np.array([8, 14, 48, 75])
print(np.gcd(a, b))
print(np.gcd(np.arange(1, 13), 12))    # which numbers share factors with 12?
[ 4  7 12 25]
[ 1  2  3  4  1  6  1  4  3  2  1 12]

In the second line, every number with result 1 is coprime with 12 (1, 5, 7, 11).

GCD of a whole array

np.gcd.reduce finds the largest number that divides every element:

python · try it yourself
import numpy as np

lengths = np.array([84, 126, 210])        # cm of three boards
piece = np.gcd.reduce(lengths)
print("longest equal piece:", piece, "cm")
print("pieces per board:", lengths // piece)
longest equal piece: 42 cm
pieces per board: [2 3 5]

Cutting each board into 42 cm pieces wastes nothing, and no longer equal length works for all three.

Simplifying fractions

Dividing numerator and denominator by their GCD gives the simplest form of a fraction:

python · try it yourself
import numpy as np

num = np.array([8, 45, 14, 9])
den = np.array([12, 60, 49, 27])
g = np.gcd(num, den)
for n, d, sn, sd in zip(num, den, num // g, den // g):
    print(f"{n}/{d} = {sn}/{sd}")
8/12 = 2/3
45/60 = 3/4
14/49 = 2/7
9/27 = 1/3

Example: aspect ratios

Screen resolutions are usually described by their aspect ratio, which is the width and height divided by their GCD:

python · try it yourself
import numpy as np

screens = np.array([[1920, 1080],
                    [1280, 1024],
                    [2560, 1600],
                    [3440, 1440]])
g = np.gcd(screens[:, 0], screens[:, 1])
ratios = screens // g[:, None]          # divide each row by its own GCD
for (w, h), (rw, rh) in zip(screens, ratios):
    print(f"{w}x{h} -> {rw}:{rh}")
1920x1080 -> 16:9
1280x1024 -> 5:4
2560x1600 -> 8:5
3440x1440 -> 43:18

g[:, None] turns the GCDs into a column, so each row of screens is divided by its own value (broadcasting, covered later in this course). The ultrawide 3440×1440 is "43:18", marketed as "21:9".

Note: Like np.lcm, np.gcd requires integer input. Negative numbers are fine: np.gcd(-12, 18) is 6.

Test yourself

What is np.gcd(24, 36)?

  1. 4
  2. 6
  3. 12
  4. 72

What does np.gcd.reduce([15, 25, 40]) return?

  1. 1
  2. 5
  3. 15
  4. 600

If gcd(a, b) = 4 and a x b = 96, what is lcm(a, b)?

  1. 4
  2. 24
  3. 96
  4. 384