Python function returning None after recursion

前端 未结 3 1716
栀梦
栀梦 2021-01-20 18:09

I can\'t figure out why this python function returns None if it calls itself recursively.

It was part of my solution to a Project Euler problem. I have solved the p

3条回答
  •  粉色の甜心
    2021-01-20 18:47

    You forgot to return a value when there is failure to find a prime:

    for div in range(2,candidate//2,1):
        if candidate % div == 0:
            prime = False
            print candidate, "is not prime - divisible by", div
            return next_prime(candidate)
    

    Recursion isn't really suitable here though. It isn't much more elegant than the simple iterative approach. Also, you could overflow the stack if you hit an area where there are lot of non-primes between two consecutive primes.

提交回复
热议问题