簡體   English   中英

在 Python 中找到沒有“中斷”的第 n 個素數

[英]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 中的stringstr數據類型。 另一方面,您的n變量是integerint數據類型。 因此,這兩個不能像您在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM