[英]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所以我一直在用 python 中的素数做一些事情,我目前正在使用这个
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?
所以我想知道是否有更快的方法来做到这一点?
关于什么:
return (number % divisor == 0)
A speed test shows that checking not()
is faster than a != 0
solution:速度测试表明检查
not()
比!= 0
解决方案更快:
%%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)
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
maybe you can use lambda
:也许你可以使用
lambda
:
isDivisible = lambda x,y: x%y==0
isDivisible(4,2)
output:输出:
True
Not faster, but note that number % divisor == 0
already returns a boolean.不是更快,但请注意
number % divisor == 0
已经返回一个布尔值。 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.
可能会稍微快一点,我还没有测试过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.