-1

So I would like to find the lowest common multiple of 4 or more numbers in python. Now I understand that in numpy, you can just use np.lcm but the function is only restricted to two inputs.

import numpy as np
result = np.lcm(12, 8) # calculating the lcm of 12 and 8
print(result)

24

The question is how do I find the lcm of 3 or more integers using the same lcm function in numpy

1 Answers1

3

You'd use np.lcm.reduce(), and pass it an array of numbers:

>>> np.lcm.reduce([1, 2, 3, 4])
12
  • how does reduce work in this sense ? – youfacejaraxxus Dec 26 '21 at 16:18
  • 1
    It basically loops over each value of the array, calling `np.lcm()` with the current value of the array, the value returned from the last call of that function. So it basically ends up as `np.lcm(np.lcm(np.lcm(np.lcm(1, 1), 2), 3), 4)` –  Dec 26 '21 at 16:21
  • 1
    @richardec Are you sure it doesn't start with `np.lcm(1, 2)`? – no comment Dec 26 '21 at 16:25
  • Yes, you're right @nocomment, apologies. –  Dec 26 '21 at 16:27
  • 1
    so Its basically `np.lcm(np.lcm(np.lcm(np.lcm(1, 2), 3), 4)` right ? – youfacejaraxxus Dec 26 '21 at 16:34
  • Exactly @DaddySinged. –  Dec 26 '21 at 16:36
  • 1
    I wasn't sure, btw. I just figured that if it does start with a neutral element, `np.lcm.reduce([])` would give me that instead of an error. Now I'm just still wondering why @DaddySinged doesn't want to use `math.lcm`... – no comment Dec 26 '21 at 16:51
  • math.lcm does not exist though ? This is all the function that exist in the math module https://www.programiz.com/python-programming/modules/math – youfacejaraxxus Dec 26 '21 at 17:25
  • @DaddySinged https://docs.python.org/3/library/math.html#math.lcm –  Dec 26 '21 at 17:28
  • @DaddySinged That page doesn't even list `math.gcd`, which was introduced in Python 3.5, over six years ago. Pretty bad. Why would you look at anything other than the official documentation? – no comment Dec 26 '21 at 17:39