Checking divisibility for multiple numbers

In Python, is there a way to check if a number is divisible by several numbers without writing out a modulo operation for each factor?

In particular, is there a better way to write this code instead of typing i% n == 0 ninety times?

if i % 11 == 0 and i % 12 == 0 and i % 13 == 0 ... and i % 100 == 0: print(i) 

Thanks!

+4
source share
5 answers

Use all() and the generator expression:

 if all(i % n == 0 for n in range(11, 101)): print(i) 
+7
source
 if all(i % n == 0 for n in reversed(xrange(11, 101))): print(i) 

Only a slightly modified version of duplicate answers has already been given: xrange returns an object that generates numbers in a range on demand (slightly faster than range and more memory efficient). If performance is important here, which is often used for mathematical pieces of code like this bit, the reverse iterator first checks for large numbers. Most likely, you will kick you out of the all() function earlier.

+4
source

You can do something like this:

 if all(i % n == 0 for n in range(11, 101)): print(i) 
+3
source

( Note: This is of mathematical interest, but previous answers are better in practice.)

You can calculate the smallest common multiple of all divisors and see if the number shares it. (Just taking the product does not work, consider N = 16 with dividers 4 and 8.)

+3
source

The above answer:

 if all(i % n == 0 for n in range(11, 101)): print(i) 

which should be mentioned as a refinement, works only with the built-in function. I use Spyder, which by default uses all of numpy.core.fromnumeric, and the above answer will not work in this case. Then use the following:

 import __builtin__ if __builtin__.all(i % n == 0 for n in range(11, 101)): print(i) 
0
source

Source: https://habr.com/ru/post/1369421/


All Articles