# Is_Prime (solved with For Loop, spoilers inside)Is recursive possible?

#1

I'm wondering how I could make my is_prime function recursive. So far I'm kind of stuck on how to turn this for loop into a more recursive function. So far I'm coming up empty.

I suspect that I may have to have two functions that call upon eachother somehow, but I'm having a hard time coming up with a possibility. Any thoughts?

``````def is_prime(x):
if x < 2:
return False
for i in range(2,x):
if x%i==0:
return False
return True

print is_prime(11)``````

Reversing a String (Recursive Solution)
#2

Yes, I believe you need a helper function that will do this part recursively:

``````  for i in range(2,x):
if x%i==0:
return False
return True``````

in your code. I called it `prime_calc` and called it in the main `is_prime` function. In the for loop, you used two numbers, i and x. So your helper will also need 2 variables and you need to increment one of them (the one that is the divisor) when you call your helper function in your helper function.

In your main function, `is_prime`, I just added the first condition:

``````if x < 2:
return False``````

And added an `else` that will call your helper (randome example below):

``````else:
return helper_function(d, c+1)``````

So, your overall structure should look something like:

``````def main(x):
if x < 2:
return False
else:
return helper(x, d) #hint hint: that i starts at 2 in your for loop..so does this d

def helper(n, a):
for i in range(2,x): #turn this for loop into recursive approach
if x%i==0:
return False
return True``````

Remember that recursion is all about cases.

#3

Thanks mate. I haven't updated my solution for Is_Prime, but I have taken your advice for the next challenge, reversing a string. Here's a link: Here

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.