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] ; % Create vector with all ints between 2 and x where
% position 1 is hard-coded as 0 since 1 is not a prime.
 
for (n = 2:sqrt(x)) % All primes factors lie between 2 and sqrt(x).
if P(n) % If the current value is not 0 (i.e. a prime),
P((2n*n):n:x) = 0 ; % then replace all further multiples of it with 0.
end
end % At this point P is a vector with only primes and zeroes.
 
P = P(P ~= 0) ; % Remove all zeroes from P, leaving only the primes.
 
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((2n*n):n:x) = false; % Multiples of n that are greater than n*n are not primes
end
end
1,336

edits