简体   繁体   中英

Python RecursionError

(I'm a total beginner) I want to write a recursive function which can tell me if a number is a prime number or not: but I keep getting the same recursion error: here is my code:


from math import *
def has_a_divider(n,p):
    if n%p==0:
        return True
    elif has_a_divider(n,(p-1))!= True:
        return False
    else:
        return False


def is_prime(a):
    if has_a_divider(a,sqrt(a))==False:
        return True
    else:
        return False

Your problem is sqrt(a) which returns a float instead of the int your code requires.
You can replace it by ceil(sqrt(a)) to get an int from it.

Also, this code does not work for finding if the number is prime as all numbers will have at least 1 has a divider. A possible solution is to update has_a_divider to check for dividers bigger than 1.

A possible implementation:

from math import ceil, sqrt
def has_a_divider(n,p):
    if p < 2:
        return False
    if n % p==0:
        return True
    return has_a_divider(n,(p-1))


def is_prime(a):
    if a == 1:
        return False

    return not has_a_divider(a,ceil(sqrt(a)))

print(is_prime(3))
print(is_prime(5))
print(is_prime(4))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM