Nash Shrestha
Nash Shrestha

Reputation: 1

Why doesn't this prime number algorithm say that 2 is not prime?

Why is it that when you input 2 into this program, it returns "2 is prime"? According to the code, if the remainder of the number divided by i, where i is any number from (and including) 2 up to the number, is equal to 0, then the number is not a prime number. But the remainder of 2 divided by 2 is 0, so why does the program say that 2 is a prime number?

# Python program to check if the input number is prime or not

# take input from the user
num = int(input("Enter a number: "))

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

# if input number is less than
# or equal to 1, it is not prime
else:
   print(num,"is not a prime number")

Upvotes: 0

Views: 91

Answers (2)

John Ruddell
John Ruddell

Reputation: 25862

because for i in range(2,2): will never be true / will not execute.

think about it range(start, stop)... the start and stop are the same so it will not enter into the for loop.

2 is a prime number but is the one case where the if statement doesn't need to be computed to determine if its a prime number

more details about pythons range function

Upvotes: 3

Jake Griffin
Jake Griffin

Reputation: 2074

range(2, 2) is actually an empty list, so the for loop doesn't iterate at all. It just jumps straight to the else clause:

>>> num = 2
>>> range(2, num)
[]
>>> for i in range(2, num):
...     print "executing loop"
... else:
...     print "done!"
... 
done!

Upvotes: 1

Related Questions