Home > Backend Development > Python Tutorial > How Can You Check if a Number is Divisible by Another in Python?

How Can You Check if a Number is Divisible by Another in Python?

Patricia Arquette
Release: 2024-11-03 15:23:30
Original
942 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template