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

不打扰是莪最后的温柔 提交于 2020-03-23 07:53:07

问题


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?


回答1:


What about:

return (number % divisor == 0)



回答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)



回答3:


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



回答4:


maybe you can use lambda:

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

isDivisible(4,2)

output:

True



回答5:


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

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

to define your funtion. This however is still the same method you are using. Could be marginlly faster, I havn't tested.



来源:https://stackoverflow.com/questions/52773914/fastest-way-to-check-if-a-number-is-divisible-by-another-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!