This very short and simple code in #Python tries to simulate the "Sieve of Eratosthenes" for the first N natural numbers with the constraints of (0) script shortness; (1) minimization of the 'if statements' and 'for/while loops'; (2) efficiency in terms of CPU time.
import numpy as np
N = 10**5
a = np.array(range(3,N,2))
for j in range(0, int(round(np.sqrt(N),0))):
a[(a!=a[j]) & (a%a[j] == 0)] = 0
a = a[a!=0]
a = [2]+list(a)
On an Intel Core I5, it returns the prime numbers among the first:
- N = 100,000 in 0.03 seconds;
- N = 1,000,000 in 0.63 seconds;
- N = 10,000,000 in 22.2 seconds.
Would someone like to share more efficient codes in term of CPU time within the aforementioned constraints?