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?
Use If/Else Statements in One Line To simplify the code and reduce the number of lines in the conditional statements, you can use an inline if conditional statement. Consider the following concise code that performs the same with one line for each if/else conditional statement.
Technically only 1 condition is evaluated inside an if , what is ascually happening is 1 condition gets evaluated and its result is evaluated with the next and so on... There is no defined limit to the length of a boolean expression; likely, you will run into memory problems at some point.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With