Python function returning None after recursion

前端 未结 3 1646
栀梦
栀梦 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 19:07

    As others have said, this is not really the place for recursion. Here is an example using iteration. I've also defined another function which tests the primality of an integer - I think this makes the code simpler.

    def is_prime(n):
        """Return True if n is prime."""
        for i in xrange(2, n//2):
            if n%i == 0:
                return False
        return True
    
    def next_prime(n):
        """Returns the next prime number after n."""
        if n % 2 == 0:
            candidate = n + 1
        else:
            candidate = n + 2
        while not is_prime(candidate):
            candidate += 2
        return candidate
    
    if __name__ == '__main__':
        n = 896576
        print next_prime(n)
    

提交回复
热议问题