Home > Article > Backend Development > How Can You Check if a Number is Divisible by Another in Python?
Divisibility Testing: Checking if a Number is Multiples of Other Numbers
Determining whether a number is a multiple of another number is a common programming task. In Python, there are a few approaches you can take to perform this check, including using the modulus operator and integer division.
Modulus Operator Approach
The modulus operator, denoted by %, returns the remainder when one number is divided by the other. Using this operator, you can check divisibility as follows:
<code class="python">if n % k == 0: # n is divisible by k</code>
For example, to test if a number is a multiple of 3, you would check if n % 3 == 0.
Integer Division Approach
Integer division in Python returns an integer result, discarding any remainder. This can be useful for testing divisibility, as a number is divisible by another if the result of integer division is an integer. In Python 2.x, integer division is performed using /, while in Python 3.x, it is done using //.
<code class="python">if n // k == int(n // k): # n is divisible by k</code>
Example Code Using the Modulus Operator
The code you provided in your question can be modified to use the modulus operator to test for divisibility by 3 and 5:
<code class="python">n = 1 s = 0 while n < 1001: if n % 3 == 0: print('Multiple of 3!') s += n if n % 5 == 0: s += n n += 1</code>
In this code, the if n % 3 == 0 and if n % 5 == 0 statements check if the current value of n is divisible by 3 or 5, respectively. If so, the sum of multiples is updated accordingly.
The above is the detailed content of How Can You Check if a Number is Divisible by Another in Python?. For more information, please follow other related articles on the PHP Chinese website!