# LCM builtin in Python / Numpy

I can write a function to find LCM (lowest common multiple) of an array of integers, but I thought it must have been implemented in numpy or scipy and was expecting something like numpy.lcm() to do that. I'm surprised to find there is no such thing. Perhaps I'm searching in a wrong place. So, if you know any other library where this simple function is defined, please oblige.

Why not define it yourself, as suggest in the Rosetta Code examples here: http://rosettacode.org/wiki/Least_common_multiple#Python

For example, you could build on this (via this library):

import fractions
def lcm(a,b): return abs(a * b) / fractions.gcd(a,b) if a and b else 0


I am not surprised at all that it's not in Numpy. Numpy is focused on floating-point and array/matrix computation, not on number theoretic functions and operations on integers. I can understand it needing internally a gcd function for some exotic array/stride computation, but it's really not the main point of the library. Sage would be the first place I'd look, not numpy.

Indeed it has this function, and it looks very fast:

sage: %timeit lcm(range(1,1000))
100 loops, best of 3: 820 µs per loop


If you are doing number theoretical computations, I'd recommend you to move to Sage instead of pure Python. You'll find that generally it has more of the stuff you need already implemented.

In Numpy v1.17 (which is, as of writing, the non-release development version) there is an lcm function that can be used for two numbers with, e.g.:

import numpy as np
np.lcm(12, 20)


or for multiple numbers with, e.g.:

np.lcm.reduce([40, 12, 20])


There's also a gcd function.

If speed is an issue, you should look at this thread: https://stackoverflow.com/questions/15569429/numpy-gcd-function It explains how you can actually easely code a quicker version of gcd (than the gcd from the fractions module) in python and then of course a lcm function from it as in the answer by blochwave.