How do I find a prime number using recursion in Python

前端 未结 6 1572
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:42

    def prime(n,j):
        if(n<2):
            return False
        if(j==n):
            return True
        if(n%j==0):
            return False
        return prime(n,j+1)
    
    print(prime(n,2))
    

    A number is called prime if it is only divisible by itself and 1. So iterate from 2 to n-1, if n is divisible by any of (2,3,4,..n-1) return False.
    If j == n then there is no such number from (2,3,4...n-1) divisible by n, Hence it's Prime.

提交回复
热议问题