Well, that's why I understand the principle of the sieve of Eratosthenes. I tried and basically couldn't write it myself (I wrote a functional prime generator, it's just inefficient or a sieve). I think I have a bigger problem with math, but the programming has mixed me up too.
import numpy as np def primesfrom2to(n): sieve = np.ones(n/3 + (n%6==2), dtype=np.bool)
Ok, write off the bat, I'm a little confused. It generates a list of truth values ββthat will be gradually marked as false because they are defined as compound. I think he says that no more than 1/3 of the values ββless than n will be simple, but what does adding the modolus operation do?
sieve[0] = False
marks 1 as false?
for i in range(int(n**0.5)
This sets the range to check. No product has a product larger than its square root. What happens to division by 3+1 ?
if sieve[i]: k=3*i+1|1
So, if sieve[i] true (why is simple / not yet marked as compound?), Then 3*i + 1 or 1 ? How it works? It seems to be generating prime numbers that will subsequently be multiplied to remove all subsequent products, but I don't know how to do this.
sieve[ ((k*k)/3) ::2*k] = False sieve[(k*k+4*k-2*k*(i&1))/3::2*k] = False
ok, so they both take primes k and mark all further multiples of them? if n=5 does not do it sieve[8.33::10] = False ? And another one like sieve[41.3::10] ? I just do not understand.
print(np.r_[2,3,((3*np.nonzero(sieve)[0]+1)|1)])
Everything is in order and, finally, it actually generates a list of primes. Again, what with multiplication by three? Obviously, there is something basic in this code that I just don't understand. Also, I again do not understand the concept of |1 .
Oh, and just for fun, here is my effective and terribly ineffective attempt.
import numpy def sieve(num): master = numpy.array([i for i in range(2, num+1)]) run = [] y=2 while y <= ((num+1)**(1/2)): thing = [x for x in range(y, num+1, y) if x > 5 or x == 4] run = run + thing y = y+1 alist = numpy.in1d(master, run, invert = True) blist = (master[alist]) print(blist)
It took 57 seconds to calculate prime numbers up to 500,000. I did the Euler sum of primes up to 2,000,000 problems.