
%  Sieve of Eratosthenes: find prime numbers up to N

clear;

%  Fill a vector A with N integers from 1 to N.

N=10000;
A=1:N;

%  Loop from 2 to N, index i. If A(i) is zero, next.
for i=2:N
    if A(i) == 0; continue; end
    %  Loop from i+1 to N with index j. If k=i*j is larger than N end this loop. Else, k is not a
    %  prime, so set A(k) to zero.
    for j=i:N
        k=i*j;
        if k>N; break; end
        A(k)=0;
    end
end
    
%  After all loops have finished, all elements of A that are not zero are prime numbers. 
%  Print them out.

k=0; m=0;
for i=1:N; 
    if A(i) > 0
        fprintf(' %d ',i);  m=m+1;
        k=k+1; if k>16; fprintf('\n'); k=0; end
    end
end

fprintf('\n\nThere are %d primes between 1 and %d\n',m,N);



