[英]How to make this recursion function for prime number more efficient
I have this code:我有这个代码:
def has_divisors(n, i=2):
"""
Check if a number is prime or not
:param n: Number to check
:param i: Increasing value that tries to divide
:return: True if prime, False if not
"""
if n <= 1:
return False
if i + 1 == n:
return True
if n <= 2 and n > 0:
return True
if n % i == 0:
return False
return has_divisors(n, i + 1)
Which tell if a number is prime or not, problem is that it can check if a number is prime up to +- 1500 after that it enters into maximum recursion depth error.判断一个数是否为素数,问题在于它可以在进入最大递归深度错误后检查一个数是否为+- 1500 以内的素数。 Does anyone has any idea how to make this code more efficient (I don't want completely different code, yes I know recursion is not a good idea for this function but I have to use it) Thank you!
有没有人知道如何使这段代码更有效(我不想要完全不同的代码,是的,我知道递归对于这个函数不是一个好主意,但我必须使用它)谢谢!
I actually made it more efficient by just adding one condition:我实际上只是通过添加一个条件来提高效率:
def has_divisors(n, i=2):
"""
Check if a number is prime or not
:param n: Number to check
:param i: Increasing value that tries to divide
:return: True if prime, False if not
"""
if n <= 1:
return False
if i == n:
return True
if n <= 2 and n > 0:
return True
if i * i > n:
return True
if n % i == 0:
return False
return has_divisors(n, i + 1)
Thanks to everyone who tried to help.感谢所有试图提供帮助的人。
Modifying function from How do I find a prime number using recursion in Python修改函数来自如何在 Python 中使用递归查找素数
This should have a maximum recursion dept > 1M这应该有一个最大递归深度> 1M
Two improvements: only goes to sqrt(N), and only checks odd numbers.两个改进:只去sqrt(N),只检查奇数。
def has_divisors(N, i=3):
if N <= 2:
return False
elif N % 2 == 0: # even
return True
elif i * i > N: # tried all divisors to sqrt,
# must be prime
return False
elif (N % i) == 0: # i is a divisor
return True
else: # recursively try the next ( odd) divisor
return has_divisors(N, i + 2)
You don't need to do basic disqualifying tests on every recursion, so to make it more efficient, as you requested, I'd cast it like:您不需要对每次递归进行基本的取消资格测试,因此为了提高效率,按照您的要求,我将其转换为:
def has_no_divisors(n):
if n <= 2 or n % 2 == 0:
return n == 2
def has_no_divisors_recursive(n, i=3):
if i * i > n:
return True
if n % i == 0:
return False
return has_no_divisors_recursive(n, i + 2)
return has_no_divisors_recursive(n)
By treating 2 as a special case and just test dividing odd numbers, this should also have twice the performance (and half the stack usage) of your revised code.通过将 2 视为特殊情况并仅测试奇数除法,这也应该具有修改后代码的两倍性能(和一半的堆栈使用量)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.