In Python, is there a way to test if a number is divisible by multiple numbers without writing out the modulo operation for each factor?
More specifically, is there
if all(i % n == 0 for n in reversed(xrange(11, 101))):
print(i)
Only a slightly modified version of the duplicate answers already given: xrange
returns an object that generates the numbers in the range on demand (slightly faster than range
and more memory efficient). If performance is important here, which it often is for mathematical code snippets like this bit, the reverse iterator will check the bigger numbers first. This is more likely to kick you out of the all()
function sooner.
Useall()
and a Generator Expression:
if all(i % n == 0 for n in range(11, 101)):
print(i)
The above answer was:
if all(i % n == 0 for n in range(11, 101)):
print(i)
which, it should be mentioned as clarification, only works with the built-in all function. I use Spyder, which by default uses the all from numpy.core.fromnumeric, and the above answer will not work in that case. Then use the following:
import __builtin__
if __builtin__.all(i % n == 0 for n in range(11, 101)):
print(i)
You could do something like this:
if all(i % n == 0 for n in range(11, 101)):
print(i)
(Note: This is of mathematical interest but the previous answers are better in practice.)
You could compute the least common multiple of all the divisors and see if the number is divisible by that. (Just taking the product doesn't work; consider N=16 with divisors 4 and 8.)