Skip to content Skip to sidebar Skip to footer

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 F

Solution 1:

What about:

return (number % divisor == 0)

Solution 2:

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)

Solution 3:

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

defisDivisible(number, divisor):
    return number % divisor == 0

Solution 4:

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.

Solution 5:

maybe you can use lambda:

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

isDivisible(4,2)

output:

True

Post a Comment for "Fastest Way To Check If A Number Is Divisible By Another In Python"