Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prime number printer stops at 251, why? [duplicate]

Tags:

python

I started learning Python today, and I came up with the idea of creating a program that prints all the prime numbers from 0 to 10 000. I managed to make my program print out all primes until 251, at which point it stops printing out numbers. Why does it do this?

Here is the code:

for numberToCheck in range(2,10000):     divider = 2     while numberToCheck > divider:         if numberToCheck % divider is 0:             break         else:             divider += 1     if numberToCheck is divider:         print(numberToCheck, "is a prime number.") 
like image 931
FopKart Avatar asked Jun 18 '16 19:06

FopKart


1 Answers

The problem is that you are using is instead of ==. The is operator performs object identity comparison, which "happens to work" for all numbers below 256 due to implementation details. 251 is the biggest prime below 256 (check here, next prime is 257) and after that the is returns False:

>>> 254 + 1 is 255 True >>> 255 + 1 is 256 True >>> 256 + 1 is 257 False 

The equality operator is ==:

>>> 254 + 1 == 255 True >>> 255 + 1 == 256 True >>> 256 + 1 == 257 True 
like image 124
Bakuriu Avatar answered Oct 04 '22 15:10

Bakuriu