## Matlab/Octave Eratosieve using minimal big-O iterations

0

I'm trying to come up with ways to write Sieve of Eratosthenes in Octave that vectorize as much as possible (ie minimizing the number of times iterating over the for-loop/while-loop/recursive call)

I found one that requires only O(log(log(n))) iterations inside the for-loop, but the big-O running time (and also space) is O(n^(5/4)/log(n)) so it's arguably not the Sieve of Eratosthenes

Now I think I have one with the usual running time O(nlog(log(n))) and only O(log(n)) iterations, but I want to see if someone else comes up with a better solution.

Question was closed 2013-03-18T18:00:52.170

You're asking us to come up with an improvement to an algorithm that dates back to ancient Greece? You might have better luck posting your code and asking for suggestions for improvement. – Mr. Llama – 2013-03-13T20:28:53.233

I'm not asking for a big-O running-time improvement. I'm just saying can you write a SOE that's better vectorized for Octave? – dspyz – 2013-03-13T22:07:51.907

1Is this really in a form appropriate for CodeGolf.SE? Perhaps it would be better on CodeReview? – dmckee --- ex-moderator kitten – 2013-03-18T18:02:21.293

0

Here's my solution The loop clearly runs O(logn) times and it's easy to see that the number of operations is bounded above by the normal number of operations for SOE(2n) so it's within O(nlog(logn)) big-O running time

function [primes] = eratosieve(n)
isprime = ones(n, 1);
isprime(1) = false;
m = 1;
while(m ^ 2 < n)
nprimes = find(isprime(m + 1 : m * 2)) + m;
mult = (m + 1) : (n/(m + 1));
a = nprimes * mult;
isprime(a(a<=n)) = false;
m *= 2;
end
primes = find(isprime);
endfunction