Reputation: 83
is it possible to make if statement shorter in this fragment of program?
for number in range(100):
if (number % 4 == 0 and number % 3 == 0 and number % 2 == 0):
Upvotes: 1
Views: 67
Reputation: 51998
Just use: if number % 12 == 0:
This is because 12 is the least common multiple of 4, 3, and 2.
On Edit:
Here is some code to compute the least common multiple of a list (or other iterable) of integers:
from math import gcd
def pair_lcm(a,b):
return a*b//gcd(a,b)
def lcm(nums):
"""computes the lcm of iterable nums"""
m = 1
for num in nums:
m = pair_lcm(m,num)
return m
For example,
>>> lcm(range(1,11))
2520
Upvotes: 5
Reputation: 742
if you don't want to do the math to combine them:
for number in range(100):
if all(number % n == 0 for n in (2, 3, 4)):
Upvotes: 1