Search code examples
pythonwhile-loopinfinite-loopprimes

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. I initially tries 277, then 13, then 5, then 3 - none of which gave a result even after a minute.

Entering 2 worked.

There must be something wrong with the code.


Solution

  • Your loop is not changing n or i, which are the conditions on which it stops.

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