Python 查找素数的 While 循环没有终止

Python While Loop To Find Prime Does Not Terminate

flag = 0
n = int(input('\nEnter whole number to check : '))
i = 2
while i <= (n/2):
    if (n%i) == 0:
        flag = 1
        break
if n == 1:
    print('1 is neither prime nor composite')
elif flag == 0:
    print(n,' is a prime number.')
elif flag == 1:
    print(n,' is not a prime number.')

输入大于等于 3 的数字后,程序停止,光标不断闪烁。我最初尝试了 277,然后是 13,然后是 5,然后是 3 - none 即使在一分钟后也给出了结果。

输入 2 有效。

一定是代码有问题。

你的循环没有改变 n 或 i,这是它停止的条件。

我认为正确的代码应该是:

flag = 0
n = int(input('\nEnter whole number to check : '))
i = 2
while i <= (n/2):
    if (n%i) == 0:
        flag = 1
        break
    i += 1
if n == 1:
    print('1 is neither prime nor composite')
elif flag == 0:
    print(n,' is a prime number.')
elif flag == 1:
    print(n,' is not a prime number.')

如果我没理解错的话,你是想检查输入的数字是否是质数。

此代码有效:

# prime numbers are greater than 1, num is the entered number
if num > 1:
   for i in range(2,num):
       if (num % i) == 0:
           print(num,"is not a prime number")
           break
else:
   print(num,"is a prime number")

最后,如果需要,您也可以检查数字1。

下面的代码有效:

flag = 0
n = int(input('\nEnter whole number to check : '))
i = 2
while i <= (n/2):
    if (n%i) == 0:
        flag = 1
        break
    else:
        i += 1
    
if n == 1:
    print('1 is neither prime nor composite')
elif flag == 0:
    print(n,' is a prime number.')
elif flag == 1:
    print(n,' is not a prime number.')

这是因为您需要在每次迭代后将 i 递增 1,否则您的 while 循环将无休止地 运行。