How do I find a prime number using recursion in Python

前端 未结 6 1590
Happy的楠姐
Happy的楠姐 2020-12-21 13:26

I have to find out whether number(N) is a prime or not using recursion, no loops are allowed. I\'ve tried converting the usual code that uses a for loop to a recursive one,

6条回答
  •  失恋的感觉
    2020-12-21 13:40

    Your function sometimes returns something and sometimes returns nothing -- it should be either all one or the other, not both. In this case is_prime() looks like a boolean function so it should return True or False. We'll leave the printing to the caller:

    def is_prime(N, a=3):
    
        if N == 2:  # special case
            prime = True
        elif N <= 1 or N % 2 == 0:  # too small or even
            prime = False
        elif a * a > N:  # tried all divisors to sqrt, must be prime
            prime = True
        elif (N % a) == 0:  # divides evenly, not a prime
            prime = False
        else:  # can't tell yet, recursively try the next (odd) divisor
            prime = is_prime(N, a+2)
    
        return prime
    
    for x in range(100):
        if is_prime(x):
            print(x)
    

    Keep it simple. Think through each possible case. Avoid increasing the indention depth unnecessarily, it makes your code more complicated.

    The above solution tries to speed up prime detection by avoiding even numbers (both divisor and number) and limiting the divisor to the square root of the number. This can matter as without these optimizations, a recursive solution will likely run out of call stack space at around N=1,000 whereas the above should go to N=1,000,000 without expanding the call stack.

提交回复
热议问题