简体   繁体   English

Python下一个质数而循环无限

[英]Python Next Prime Number While Loop Infinite

So I have made a code for generating a next prime number, for example if I input the number 4 it will give me the input 5 or 25 it will give me the input 29.所以我编写了一个生成下一个质数的代码,例如,如果我输入数字 4,它会给我输入 5 或 25,它会给我输入 29。

The problem I get is that I can't seem to get the while loop to close, it goes on forever, is there anyway to close this while loop so that it does iterate infinitely.我遇到的问题是我似乎无法关闭 while 循环,它会一直持续下去,无论如何要关闭这个 while 循环,以便它无限迭代。

I have also tried using breaks to end the code but then the code doesn't output the right input.我也尝试使用中断来结束代码,但代码没有输出正确的输入。 For example after putting a break the code then would input 27 as a prime when I inputted 25. This is wrong since I know 27 is not a prime number.例如,当我输入 25 后,代码会输入 27 作为质数。这是错误的,因为我知道 27 不是质数。

X = int(input())
Prime = True

while Prime:
    for i in range(2,X):
        KK = X % i
        if KK == 0:
            X+=1
        else:
            print(X)
            Prime = True

As others have mentioned, the loop will never end.正如其他人所说,循环永远不会结束。

Below is a naive solution for reference.下面是一个幼稚的解决方案供参考。
Obviously, incrementing the running variable by 1 and checking if it is prime is a bad strategy.显然,将运行变量增加 1 并检查它是否为素数是一个糟糕的策略。
Also, there are better prime number checkers out there.此外,还有更好的质数检查器。

def isPrime(num):
    for i in range(2, num//2): 
        if (num % i) == 0: 
            return False
    return True

X = int(input()) 
while not isPrime(X):
    X += 1
print(X)

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

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