MATLAB: Getting a while loop to loop around

loopprimessievewhile

Hi there, I'm trying to make a prime sieve, without using the functions primes(n) or isprime and I'm having trouble with getting my while loop to loop around.
% code
function [p,c] = sieve(N)
X=ones(1,N);
A=ceil(sqrt(N));
p=[1:N];
D=[2:A];
m=1;
n=1;
while (m<=N && n<=A && p(m)<D(n))
if mod(p(m),D(n))==0
p(m)=0
X(m)=0
n=n+1
else
m=m+1
end
p
c=cumsum(X)
end

Best Answer

Trace your code through.
m = 1, n = 1, p(m) < D(n) is 1 < 2 which is true . mod(1,2)~=0 so we hit the else, which increments m to 2. Now p(m) < D(n) is 2 < 2 which is false, so your loop ends. Perhaps you should not be testing p(m) < D(n) there.
I notice, by the way, that you do not reset n when m increments.
Related Question