How do I find a prime number using recursion in Python

前端 未结 6 1592
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:48

    Your solution is close, with just a few changes needed to make it work.

    def is_prime(a,N):
        print(a, N)
        if N <= 1:
            return 
        else:
            if a >= N:
                print(N)
            else:
                if N == 2: 
                    print(N)
                elif (N % a) == 0:
                    return False
                else:
                    return is_prime(a+1,N)
    
        return False
    

    You didn't give any examples of calling this function, but I assume it's always called with a being 2, since any other value wouldn't make sense. So if you run the above function like so, you should get the right output:

    print(is_prime(2, 7))  => True
    print(is_prime(2, 4))  => False
    print(is_prime(2, 37)) => True
    

    I think you have a misunderstanding of how recursion works, you're assigning this prime variable in the body of the function, but never doing anything with it. Maybe your confusion comes from a misunderstanding of scopes in Python. That prime variable will not be 'shared' across invocations, it will just create a new prime every time.

    EDIT: Didn't realize you wanted the function to just print out the prime if it's a prime, changed the code accordingly.

提交回复
热议问题