Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing divisibility by multiple numbers

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!

like image 653
kennysong Avatar asked Aug 29 '11 01:08

kennysong


People also ask

How do you test if a number is divisible by another number?

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.

What is the rule of test of divisibility?

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.

How do you find the divisibility of all numbers?

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.

What is the test for divisibility of 2 and 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.


2 Answers

Useall()and a Generator Expression:

if all(i % n == 0 for n in range(11, 101)):
    print(i)
like image 68
pillmuncher Avatar answered Sep 28 '22 07:09

pillmuncher


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.

like image 28
wim Avatar answered Sep 28 '22 07:09

wim