简体   繁体   English

在 Python 中找到没有“中断”的第 n 个素数

[英]Finding the nth prime number without 'break' in Python

I'm quite new to coding and I'm being asked to write code to find the nth prime number in Python.我对编码很陌生,我被要求编写代码来查找 Python 中的第 n 个素数。 I managed to writing the following code:我设法编写了以下代码:

prime = input("which prime do you want to find?:")

n = 0
for x in range(2, 8000):
    for y in range (2, x):
        if (x % y) == 0:
            break
    else:
        n = n + 1
    if n == prime:
        print(x)
        break

However, I just found out I'm not allowed to use break.但是,我刚刚发现我不允许使用break。 They're essentially only allowing me 'for' and 'while' loops.他们基本上只允许我“for”和“while”循环。 Does anyone have any inkling on how to do this?有没有人知道如何做到这一点?

Here's how to do this with while loops and no use of break :以下是使用while循环而不使用break的方法:

# Let's find the first prime equal to or greater than the number input by the user

# Get the user's input
prime = input("which prime do you want to find?:")

found = False
x = 2
# While we haven't found the prime we're looking for and we haven't reached our upper limit...
while not found and x < 8000:
    # See if we can find any factors for 'x', the next number we're considering
    y = 2
    while not found and y < x:
        # While we haven't found a factor and still have more candidates...
        if (x % y) == 0:
            # We found a factor, so note that we have done so.  This will exit the inner
            # while loop that we're in.
            found = True
        else:
            # Not a factor, so try the next factor candidate
            y += 1
    if not found and x >= int(prime):
        # If we didn't find any factors, and the current candidate is equal to or
        # greater than the user's input, then 'x' is the prime we're looking for,
        # so set 'found' to True to exit the outer loop.
        found = True
    else:
        # Otherwise, make sure 'found' is false (it may already be) and move on to the next candidate
        found = False
        x += 1
        
print(x)

I think this version has some value.我认为这个版本有一些价值。 It shows one reason why having break is valuable.它显示了break很有价值的原因之一。 Not being able to use break , this solution is considerably more cumbersome since we have to explicitly keep track of the current values for each loop and we also have to test and set a flag to decide if we should keep iterating.不能使用break ,这个解决方案要麻烦得多,因为我们必须明确地跟踪每个循环的当前值,我们还必须测试并设置一个标志来决定我们是否应该继续迭代。 This is NOT the way this problem should be solved in the real world!这不是在现实世界中解决这个问题的方式! One should use for loops and break instead.应该使用for循环和break来代替。

I'm afraid you'll need to refactor the whole code.恐怕您需要重构整个代码。 Otherwise, with this current code you'll get some errors that are not even related to the prime finding logic.否则,使用此当前代码,您将得到一些甚至与主要查找逻辑无关的错误。

For instance, the input you are storing in prime variable is by default a string or str data type in python.例如,您存储在prime变量中的输入默认情况下是 python 中的stringstr数据类型。 On the other hand your n variable is an integer or int data type.另一方面,您的n变量是integerint数据类型。 So these two cannot be compared like you did in if n==prime which can be fixed by replacing it with if n==int(prime) , by converting the prime variable to int data type.因此,这两个不能像您在if n==prime中所做的那样进行比较,可以通过将其替换为if n==int(prime)来修复,方法是将prime变量转换为int数据类型。 You can also convert that while taking the input like this:您也可以在输入这样的输入时转换它:

prime = int(input("which prime do you want to find?:"))

There is an indentation fault too, but since your post was edited by someone else maybe it wasn't your fault.也有缩进错误,但是由于您的帖子是由其他人编辑的,所以这可能不是您的错。

However, you could use a better algorithm to find the n-th prime.但是,您可以使用更好的算法来找到第 n 个素数。 Nested loops can hurt you so bad because it makes the program too slow, particularly in python.嵌套循环会对你造成很大的伤害,因为它会使程序太慢,尤其是在 python 中。 You can checkout some algorithms like Sieve of Eratosthenes , if you don't know them already.如果您还不了解它们,您可以查看一些算法,例如Eratosthenes 的 Sieve

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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