简体   繁体   English

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.')

Upon Entering a number >= 3, the program stalls and the cursor keeps blinking endlessly.输入数字 >= 3 后,程序停止,cursor 不断闪烁。 I initially tries 277, then 13, then 5, then 3 - none of which gave a result even after a minute.我最初尝试了 277,然后是 13,然后是 5,然后是 3 - 即使在一分钟后,它们都没有给出结果。

Entering 2 worked.输入 2 有效。

There must be something wrong with the code.代码一定有问题。

Your loop is not changing n or i, which are the conditions on which it stops.您的循环不会改变 n 或 i,这是它停止的条件。

I think the correct code should be:我认为正确的代码应该是:

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.')

If I understand correctly, you're trying to check if a number entered is a prime number.如果我理解正确,您正在尝试检查输入的数字是否为质数。

This code works:此代码有效:

# 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")

At the end, you can also check for number 1 if you want.最后,您还可以根据需要检查数字 1。

The code below works:下面的代码有效:

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.')

This is because you need to increment i by 1 after every iteration, or your while loop will run endlessly.这是因为您需要在每次迭代后将i增加 1,否则您的 while 循环将无休止地运行。

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

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