Search code examples
pythonintegermodulo

How do you check whether a number is divisible by another number?


I need to test whether each number from 1 to 1000 is a multiple of 3 or a multiple of 5.

I tried this code in Python 2.x:

n = 0
s = 0

while (n < 1001):
    x = n/3
    if isinstance(x, (int, long)):
        print 'Multiple of 3!'
        s = s + n
    if False:
        y = n/5
        if isinstance(y, (int, long)):
            s = s + n

    print 'Number: '
    print n
    print 'Sum:'
    print s
    n = n + 1

The idea is to try dividing the number and see if the result is an integer. However, I'm not getting the expected result.

How do I test whether the number is an integer?


In 2.x, division like this will produce an integer, discarding the remainder; see How can I force division to be floating point? Division keeps rounding down to 0? for details.

In 3.x, the division will produce a floating-point value; the result is not "an integer" even if it is a whole number, so the isinstance check will fail. See Why does integer division yield a float instead of another integer? for details.

If you need the remainder from integer division rather than just testing for divisibility, see Find the division remainder of a number.


Solution

  • You do this using the modulus operator, %

    n % k == 0
    

    evaluates true if and only if n is an exact multiple of k. In elementary maths this is known as the remainder from a division.

    In your current approach you perform a division and the result will be either

    • always an integer if you use integer division, or
    • always a float if you use floating point division.

    It's just the wrong way to go about testing divisibility.