[英]Finding the nth prime number without 'break' in Python
我对编码很陌生,我被要求编写代码来查找 Python 中的第 n 个素数。 我设法编写了以下代码:
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
但是,我刚刚发现我不允许使用break。 他们基本上只允许我“for”和“while”循环。 有没有人知道如何做到这一点?
以下是使用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)
我认为这个版本有一些价值。 它显示了break
很有价值的原因之一。 不能使用break
,这个解决方案要麻烦得多,因为我们必须明确地跟踪每个循环的当前值,我们还必须测试并设置一个标志来决定我们是否应该继续迭代。 这不是在现实世界中解决这个问题的方式! 应该使用for
循环和break
来代替。
恐怕您需要重构整个代码。 否则,使用此当前代码,您将得到一些甚至与主要查找逻辑无关的错误。
例如,您存储在prime
变量中的输入默认情况下是 python 中的string
或str
数据类型。 另一方面,您的n
变量是integer
或int
数据类型。 因此,这两个不能像您在if n==prime
中所做的那样进行比较,可以通过将其替换为if n==int(prime)
来修复,方法是将prime
变量转换为int
数据类型。 您也可以在输入这样的输入时转换它:
prime = int(input("which prime do you want to find?:"))
也有缩进错误,但是由于您的帖子是由其他人编辑的,所以这可能不是您的错。
但是,您可以使用更好的算法来找到第 n 个素数。 嵌套循环会对你造成很大的伤害,因为它会使程序太慢,尤其是在 python 中。 如果您还不了解它们,您可以查看一些算法,例如Eratosthenes 的 Sieve 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.