Skip to main content

gcd and lcm

math.gcd and math.lcm return the greatest common divisor and least common multiple of integers; both accept any number of arguments (3.9+). Use them for reducing fractions, slope normalization (max points on a line) and array-wide gcd problems.

Syntax​

import math

math.gcd(12, 18) # -> 6 O(log min(a, b))
math.lcm(4, 6) # -> 12

Variadic (3.9+)​

import math

math.gcd(12, 18, 24) # -> 6
math.lcm(2, 3, 4) # -> 12
math.gcd() # -> 0 identity
math.lcm() # -> 1

gcd / lcm of a list​

import math

nums = [24, 36, 60]
math.gcd(*nums) # -> 12
math.lcm(*nums) # -> 360

Reduce a fraction​

import math

def reduce_frac(num: int, den: int) -> tuple[int, int]:
g = math.gcd(num, den)
num, den = num // g, den // g
if den < 0: # normalize sign so keys are canonical
num, den = -num, -den
return num, den

reduce_frac(6, -8) # -> (-3, 4)

Slope as a hashable key (LC 149)​

import math

def slope(p: tuple[int, int], q: tuple[int, int]) -> tuple[int, int]:
dx, dy = q[0] - p[0], q[1] - p[1]
g = math.gcd(dx, dy) # gcd is always >= 0, gcd(0, 0) == 0
dx, dy = dx // g, dy // g
if dx < 0 or (dx == 0 and dy < 0):
dx, dy = -dx, -dy
return dx, dy

slope((0, 0), (2, 4)) == slope((1, 2), (0, 0)) # -> True

Manual Euclid​

def gcd(a: int, b: int) -> int:
while b:
a, b = b, a % b
return a

gcd(48, 18) # -> 6
lcm = lambda a, b: a // gcd(a, b) * b # divide first to keep numbers small

Docs​