You can simplify by using just one matrix $$P(i,j)=6ij+i-j$$ with $i\geq 2$ and $j\geq 1$ We can find primes (except $2$ , $3$ and $5$) simply by picking numbers $k>1$ which do not appear in this array (except $21$) with: $p= \frac{(6k-1)}{5}$ if $k\equiv 1 \bmod 5$ and $p=6k-1$ otherwise However a faster method is obtained using this code in python: n=10000000 primes5m6 = [True] * (n//6+1) primes1m6 = [True] * (n//6+1) for i in range(1,int((n**0.5+1)/6)+1): if primes5m6[i]: primes5m6[6*i*i::6*i-1]=[False]*((n//6-6*i*i)//(6*i-1)+1) primes1m6[6*i*i-2*i::6*i-1]=[False]*((n//6-6*i*i+2*i)//(6*i-1)+1) if primes1m6[i]: primes5m6[6*i*i::6*i+1]=[False]*((n//6-6*i*i)//(6*i+1)+1) primes1m6[6*i*i+2*i::6*i+1]=[False]*((n//6-6*i*i-2*i)//(6*i+1)+1) where for $i>0$ $ p = 6i-1 $ is prime if $ primes5m6 [i] = True $ and $ p = 6i + 1 $ is prime if $ primes1m6 [i] = True $