0

I want to get a prime number list. 15 should not occur as per the definition of prime number. But it showed on my output. I don't know what happened. python

import math
n = input('n')
n = int(n)

A = list(range(2,n+1))
print(A)
n_=math.floor(math.sqrt(n))
m = list(range(2,n_+1))
for i in range(0,len(m)):
    if m[i]!=0:
        j = m[i]^2
        while j<= n:
            A[j-2] = 0
            j = j+m[i]


A[0]=2;
print(A)
print(m)

I expect the output to be [2, 3, 0, 5, 0, 0, 0, 9, 0, 11, 0, 0, 0, 0, 0, 17, 0, 0, 0]

Actual output is [2, 3, 0, 5, 0, 0, 0, 9, 0, 11, 0, 0, 0, 15, 0, 17, 0, 0, 0]

blhsing
  • 91,368
  • 6
  • 71
  • 106
Joey
  • 9
  • 2
  • What method are you trying to use? Kinda looks like a sieve but I'm confused... – John Krakov Mar 22 '19 at 22:33
  • sorry the expected output should be [2, 3, 0, 5, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 17, 0, 0, 0], something happens with 3, but I could not find out the problem. lol – Joey Mar 22 '19 at 22:33
  • 1
    But what math do you rely on? – John Krakov Mar 22 '19 at 22:35
  • It's a sieve !! sorry for forgetting to mention that – Joey Mar 22 '19 at 22:36
  • well ... 7 is a prime, 13 is a prime, 19 is a prime, ... – Patrick Artner Mar 22 '19 at 22:39
  • Ok fine, then I think you've got a problem on the math side of things. Take a look a the wikipedia page for sieve of erathostene for a great pseudocode – John Krakov Mar 22 '19 at 22:43
  • 1
    Thank you... I am just starting to learn algorithms. I implement the pseudocode as per the pseudocode on the book, but it didn't give me the right answer lol. Maybe I didn't really catch the idea lol Thanks again for pointing out the error. I'll check wikipedia :D – Joey Mar 22 '19 at 22:48
  • [sieve-of-eratosthenes-finding-primes-python](https://stackoverflow.com/questions/3939660/sieve-of-eratosthenes-finding-primes-python) – Patrick Artner Mar 22 '19 at 22:58
  • finally I found that I made a mistake in m[i]^2 it seems that it isn't m[i] square, I mix up matlab and python lol – Joey Mar 22 '19 at 23:09
  • Yeah, Python exponentiation is `**`. – user2357112 Mar 22 '19 at 23:15

0 Answers0