1

My code works to give most primes, however it still include 1 and misses some numbers: 23 and 47 (when calculating prime numbers under 100). For some reason it includes 91, any ideas why?? I have been using the Wikipedia instructions for the Sieve of Atkin.

My code is as follows:

limit = 100
results = [2, 3, 5] #prime numbers
sieve = [i for i in range(limit + 1)] #numbers to test
TF = [False] * (limit + 1) #marks number as prime or not
ModFour = [1, 13, 17, 29, 37, 41, 49, 53]
ModSix = [7, 19, 31, 43]
ModTwelve = [11, 23, 47, 59]

for x in range(limit + 1):
    for y in range(limit + 1):
        test = 4 * x**2 + y**2 
        if test % 60 in ModFour:
            try:
                TF[test] = True
            except IndexError:
                pass 
        test = 3 * x**2 + y**2
        if test % 60 in ModSix:
            try:
                TF[test] = True
            except IndexError:
                pass 
        if x > y:
            test = 3 * x**2 - y**2
            if test % 60 in ModTwelve:
                try:
                    TF[test] = True         
                except IndexError:
                    pass 

for n in range(2, limit + 1):
    if TF[n] == True:
        for x in range((n**2), (limit + 1), (n**2)):
            TF[x] = False


for p in range(limit + 1):
    if TF[p] == True:
        results.append(sieve[p])


for prime in results:
    print prime         

Any suggestions on optimisation of the sieve are welcome. Thanks

Will Ness
  • 70,110
  • 9
  • 98
  • 181
Tom
  • 918
  • 6
  • 19
  • Have you compared your code to [this similar problem](http://stackoverflow.com/questions/21783160/sieve-of-atkin-implementation-in-python)? Check where your logic deviates from his. – WGS Jan 29 '15 at 18:06
  • @TheLaughingMan : Mine is different when I do - if test % 60 in ModFour(etc) -. However I don't know why his works but mine doesn't. He is also using a optimised version because his ranges go to the square root of limit + 1. – Tom Jan 29 '15 at 18:11

1 Answers1

1

You are not flipping TF[test] - you are just setting those elements to True. Compare against the code at (this SO question):

test = 4 * x**2 + y**2    | n = 4*x**2 + y**2
if test % 60 in ModFour:  | if n<=limit and (n%12==1 or n%12==5):
  try:                    |  
    TF[test] = True       |   is_prime[n] = not is_prime[n]
  except IndexError:      | 
    pass                  |

To remove the 1 from results, just start at TF[5] when building the results list:

for p in range(5, limit + 1):
    if TF[p] == True:
        results.append(sieve[p])
Community
  • 1
  • 1
ErikR
  • 51,541
  • 9
  • 73
  • 124