Categories
integer modulo python

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

168

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.

4

322

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.

3

  • 0 % 5 == 0 would be True as well, but zero is not exact multiple of zero.

    – Fusion

    Aug 9, 2017 at 12:41

  • 7

    @Fusion 0 == 0*5

    Feb 20, 2018 at 23:37

  • @Chris_Rands Put that into an answer, people who do code-golf (like me) would be very happy. In fact, I came here looking for a golfed answer like that.

    Nov 11, 2018 at 22:29

15

You can simply use % Modulus operator to check divisibility.
For example: n % 2 == 0 means n is exactly divisible by 2 and n % 2 != 0 means n is not exactly divisible by 2.

    1

    You can use % operator to check divisiblity of a given number

    The code to check whether given no. is divisible by 3 or 5 when no. less than 1000 is given below:

    n=0
    while n<1000:
        if n%3==0 or n%5==0:
            print n,'is multiple of 3 or 5'
        n=n+1