Skip to content

Commit 9244e32

Browse files
authored
Merge pull request #82 from MaximSmolskiy/improve_sieve_of_eratosthenes
Improve sieve of Eratosthenes
2 parents d53d76c + 47a88b5 commit 9244e32

File tree

1 file changed

+9
-14
lines changed

1 file changed

+9
-14
lines changed

algorithms/Sieve_of_Eratosthenes/sieveER.m

+9-14
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,18 @@
33
function y = sieveER(N)
44
% precondition
55
assert(N >= 2,"N must be >= 2")
6-
tmp = 2:1:N; % all numbers from 2 up to N
7-
y = []; % the answer
6+
tmp = [false,true(1,N-1)]; % indexed by all numbers from 2 up to N
87

9-
% labels all composite number with 0
10-
for i = 1 : 1 : length(tmp)
11-
for j = i+1 : 1 : length(tmp)
12-
if (mod(tmp(j),tmp(i)) == 0)
13-
tmp(j) = 0;
14-
endif
15-
endfor
8+
% labels all composite number with false
9+
for i = 2 : 1 : sqrt(N)
10+
if (tmp(i))
11+
for j = i^2 : i : N
12+
tmp(j) = false;
13+
endfor
14+
endif
1615
endfor
1716

1817
% fills up all prime numbers in vector y
19-
for i = 1 : 1 : length(tmp)
20-
if (tmp(i) ~= 0)
21-
y = [y tmp(i)];
22-
endif
23-
endfor
18+
y = find(tmp);
2419

2520
endfunction

0 commit comments

Comments
 (0)