How do I find a prime number using recursion in Python

前端 未结 6 1603
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:49

    def is_prime(n):
      def prime_helper(n, x):
        if n == 1:
          return False
        elif n % x == 0:
          return False
        else:
          return prime_helper(n , x+1) if x * x <= n else True 
      return prime_helper(n, 2)
    

    if you don't want to use a helper function

    def is_prime(n, x=2):
        if n == 1:
          return False
        elif n % x == 0:
          return False
        else:
          return is_prime(n , x+1) if x * x <= n else True 
    

    Also, you don't need to check all the numbers between (1 - N) but only up to sqrt(n). You can change your iterative approach to

    for loop

    from math import sqrt 
    def is_prime(n):
      if n == 1:
         return False
      for i in range(2, round(sqrt(n)) + 1):
         if n % i == 0:
            return False
      return True
    

    while loop

    def is_prime(n):
      if n == 1:
        return False
      i = 2
      while i * i <= n:
         if n % i == 0:
            return False
         i += 1
      return True
    

提交回复
热议问题