Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to check if a number is divisible by another in python

So I’ve been doing something with primes in python, and I’m currently using this

def isDivisible(number,divisor):
    if number % divisor == 0:
        return True
    return False

to check if a number is divisible by the divisor. So I was wondering if there was a faster way to do this?

like image 726
DanDeg Avatar asked Oct 12 '18 06:10

DanDeg


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.

How do you check if something is divisible by 3 in Python?

To determine if a number is divisible by 3 using Python, we divide by 3. If the remainder after division is 0, then the number is the number is divisible by 3. If it is not 0, then the number is not divisible by 3.

How do you check divisibility by 7 in Python?

if cnt % 7 = = 0 and cnt % 5 = = 0 : print (cnt, " is divisible by 7 and 5." ) Output: 35 is divisible by 7 and 5.


5 Answers

What about:

return (number % divisor == 0)
like image 199
Dominique Avatar answered Oct 25 '22 17:10

Dominique


A speed test shows that checking not() is faster than a != 0 solution:

%%timeit 
not(8 % 3)
# 19 ns ± 0.925 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

%%timeit 
8 % 3 != 0
# 27.1 ns ± 0.929 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
like image 25
andrew_reece Avatar answered Oct 25 '22 16:10

andrew_reece


I doubt there is a "faster" way of checking this. And it seems pretty simple. However, I would write your function as:

def isDivisible(number, divisor):
    return number % divisor == 0
like image 29
AGN Gazer Avatar answered Oct 25 '22 18:10

AGN Gazer


Not faster, but note that number % divisor == 0 already returns a boolean. So you could simply do:

is_divisible = lambda number, divisor: number % divisor == 0

to define your function. This however is still the same method you are using. Could be marginally faster, I haven't tested.

like image 36
Puff Avatar answered Oct 25 '22 18:10

Puff


maybe you can use lambda:

isDivisible = lambda x,y: x%y==0

isDivisible(4,2)

output:

True
like image 28
Sociopath Avatar answered Oct 25 '22 18:10

Sociopath