简体   繁体   English

如何使用单参数Python递归确定素数

[英]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:这当然不是查找素数的最有效方法,但可以通过将您在问题中描述的“基本思想”转换为算法来使用递归来完成:

  • If x >= 3, run through all integers i from 2 to sqrt(x):如果 x >= 3,则遍历从 2 到 sqrt(x) 的所有整数 i:
    • Check if i is prime (using this function recursively).检查 i 是否为素数(递归使用此函数)。
      • If yes, check if x can be evenly divided by i.如果是,请检查 x 是否可以被 i 整除。
        • If yes, then x is not a prime number (exit function).如果是,则 x 不是素数(退出函数)。
        • If no, continue.如果没有,请继续。
      • If no, continue.如果没有,请继续。
  • If we have run through all i and the function is still running, then x was not divisible by any of the prime i, so x is a prime number.如果我们已经遍历了所有的 i 并且函数仍在运行,那么 x 不能被任何一个质数 i 整除,所以 x 是一个质数。
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM