简体   繁体   English

在python中检查一个数字是否可以被另一个数字整除的最快方法

[英]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.

相关问题 检查 python 中的数字是否可被另一个整除 - Check if a number is divisible by another in python 如何检查数字是否可以被另一个 Python 整除 - How to check if the number is divisible by another one Python 检查列表中的数字是否可被另一个数字整除的最有效方法 - Most efficient way to check if numbers in a list is divisible by another number Python:检查区间数所在的最快方法 - Python: fastest way to check in which interval number is in 什么是检查一个数字是否在规定的范围内蟒最快的方法是什么? - What is the fastest way to check if a number is in specific range in python? 你如何检查一个数字是否可以被另一个数字整除? - How do you check whether a number is divisible by another number? 如何编写一个将接受数字的程序,并通过不将数字除以5来检查其是否可以被5整除(在python中) - how to write a program that will take a number and check if it is divisible by 5 or not by not dividing the number by 5 (in python) 如何在Jinja模板(Django Framework)中检查数字是否可被另一个数整除 - How to check whether a number is divisible by another in Jinja Template (Django Framework) 有没有办法(永远)检查某个字符串的长度是否可以被某个数字整除? - Is there a way to check (forever) if the length of a certain string is divisible by a certain number? 如何检查数字是否可以被列表中的元素之一整除(Python)? - How can I check if a number is divisible by one of the elements in a list (Python)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM