Sieve of Eratosthenes: Difference between revisions
m
→{{header|MATLAB}}: multiples less than n*n are already removed by earlier iterations
No edit summary |
m (→{{header|MATLAB}}: multiples less than n*n are already removed by earlier iterations) |
||
Line 6,214:
function P = erato(x) % Sieve of Eratosthenes: returns all primes between 2 and x
P = [0 2:x]
% position 1 is hard-coded as 0 since 1 is not a prime.
for
if P(n) % If the current value is not 0 (i.e. a prime),
P(
end
end % At this point P is a vector with only primes and zeroes.
P = P(P ~= 0)
return</lang>The optimization lies in fewer steps in the for loop, use of MATLAB's built-in array operations and no modulo calculation.
Line 6,237:
for n = 2:sqrt(x)
if ISP(n)
ISP(
end
end
|