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 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!
A number is divisible by another number if it can be divided equally by that number; that is, if it yields a whole number when divided by that number. For example, 6 is divisible by 3 (we say "3 divides 6") because 6/3 = 2, and 2 is a whole number.
A divisibility test is an easy way to identify whether the given number is divided by a fixed divisor without actually performing the division process. If a number is completely divided by another number, then the quotient should be a whole number and the remainder should be zero.
2: If the number is even or end in 0,2,4, 6 or 8, it is divisible by 2. 3: If the sum of all of the digits is divisible by three, the number is divisible by 3. 4: If the number formed by the last two digits is divisible by 4, the number is divisible by 4. 5: If the last digit is a 0 or 5, the number is divisible by 5.
The easiest divisibility tests are for 2 and 5. A number is divisible by 2 if its last digit is even, and by 5 if its last digit is 0 or 5.
Useall()
and a Generator Expression:
if all(i % n == 0 for n in range(11, 101)):
print(i)
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.
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