I am trying to create a function to determine whether a number is a prime number or not. However, I can only use one parameter in the function. Here is what I have so far, but I am not sure how to do the recursion part to make it return to the right value.
The question is "Write a recursive function "IsPrime(x)" to determine whether x (a positive integer) is a prime number or not. If it is prime, return True; otherwise, return False. The basic idea is that for all x >= 3, if x cannot be evenly divided by any prime integer less than or equal to sqrt(x), then it is a prime number. Again, do not use a built-in Python function. Instead, write your own code to achieve it."
def IsPrime(x):
if x == 1:
return False
elif x == 2:
return True
else:
return IsPrime(math.floor(math.sqrt(x)))
This is of course not the most efficient way to find prime numbers, but it can be done with recursion, by turning the "basic idea" you describe in the question into an algorithm:
import math
def IsPrime(x):
if x == 1:
return False
if x == 2:
return True
for i in range(2, math.floor(math.sqrt(x)) + 1):
if IsPrime(i):
if x % i == 0:
return False
return True
Note that whenever a return
statement is reached, the execution of the function is terminated. This allows us to omit the explicit else
statement, for example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.