File tree 1 file changed +9
-14
lines changed
algorithms/Sieve_of_Eratosthenes
1 file changed +9
-14
lines changed Original file line number Diff line number Diff line change 3
3
function y = sieveER(N )
4
4
% precondition
5
5
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
8
7
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
16
15
endfor
17
16
18
17
% 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 );
24
19
25
20
endfunction
You can’t perform that action at this time.
0 commit comments