[英]How to determine prime number using recursion with single parameter Python
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."问题是“写一个递归函数“IsPrime(x)”来判断x(一个正整数)是否是素数,如果是素数,则返回True;否则返回False。基本思想是对于所有x >= 3,如果x不能被任何小于或等于sqrt(x)的素数整除,则它是素数。同样,不要使用内置的Python函数。而是编写自己的代码来实现它。”
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.请注意,无论何时到达return
语句,函数的执行都会终止。 This allows us to omit the explicit else
statement, for example.例如,这允许我们省略显式的else
语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.