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,
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
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
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