I was trying to implement Eratosthenes sieve without "cheating" and looking it up online. What i found was that my script works, i.e. returns the correct numbers, BUT it was sooo slow, took like 25-30 minutes to complete for N=2000000.
This other smaller script I found online was much faster — timed .6 seconds.
Can someone maybe explain what it is that eats up so much time in script compared to the smaller one?
%%fast script
N = 2000000;M = 1:N;p = M(2);while p^2 < N M(p^2:p:N) = 0; p = find(M>p,1);endprimes = M(M>1);%%my slow script
clearE = 2000000;M = (2:E);i = 1;p = M(i);K = [];while p^2 < E K = []; if p ~= 0 for k = p^2-1:p:length(M) if mod(M(k),p) == 0 K = [K,k]; end end M(K) = 0; end i = i + 1; if i <= E-1 p = M(i); else break; end end M = M(M>0);
Best Answer