How can I reduce the number of conditions in a statement?

Viewed 164

In this exercise I need to come up with a way to find the least common multiple (LCM) for the first 20 natural numbers (1-20). So far this is what I got:

if exercise == 34:
    lcm = 20
    while lcm % 2 != 0 or \
            lcm % 3 != 0 or \
            lcm % 4 != 0 or \
            lcm % 5 != 0 or \
            lcm % 6 != 0 or \
            lcm % 7 != 0 or \
            lcm % 8 != 0 or \
            lcm % 9 != 0 or \
            lcm % 10 != 0 or \
            lcm % 11 != 0 or \
            lcm % 12 != 0 or \
            lcm % 13 != 0 or \
            lcm % 14 != 0 or \
            lcm % 15 != 0 or \
            lcm % 16 != 0 or \
            lcm % 17 != 0 or \
            lcm % 18 != 0 or \
            lcm % 19 != 0 or \
            lcm % 20 != 0:
        lcm += 1
    print(lcm)

Is there a more efficient, to code this without the need to write a condition for every potential number to be factored in the loop?

2 Answers

Here is a shorter version, replace long or with any

if excercise == 34:
    lcm = 20
    while any(lcm % i != 0 for i in range(2, 21)):
        lcm += 1
    print(lcm)

I'd say best way will be this:

>>> math.lcm(*range(1, 21))
232792560

As the result is fairly large, your += 1 loop will take quite long no matter how nice others make it.

Best way before Python 3.9 might be something like this:

>>> def lcm(a, b):
        return a * b // math.gcd(a, b)

>>> functools.reduce(lcm, range(1, 21))
232792560

Both ways take only a few microseconds.

Or... with a little bit of head work, you could just multiply the largest powers of all primes in that range:

>>> 16*9*5*7*11*13*17*19
232792560
Related