# Matlab Program Not Executing SQRT to find primes

#### Dapnc

Joined Feb 7, 2013
3
Hi. Working in Matlab. Trying to write a program to find prime numbers without using the Prime, iprime, factor, etc command. No matter where I place the square root I cannot get the program to execute it. So, I continue to end up with a list of odd numbers instead of prime.
Any suggestions? New Matlab user. I know I removed all evens and left with odds but when I try to manipulate to take the primes out from the odds it is not working. Thank you. Just need some hints.

clear;
clc;
tic;
N=15 %largest number in list
R=linspace (1,N,N) %starting list - all numbers up to n - Matlab
%linspace calculates the space evenly between elements 1=starting value,
%N=largest value, N=total
nextprime=2 %starting with 2
if (nextprime*nextprime) <N %quit once through all numbers
end

for k=2:N %starts at 2 to start looking for prime

if nextprime*k <=N %don't exceed length of vector
R(nextprime*k) = 0 % 0 if even

end
end
% end %this is taking out all the even numbers

%trying to get prime only numbers --THIS IS WHERE MY PROBLEM IS
for n=2:N %starts at 2 to start prime ???

if R (nextprime+n) <=0 %go up list until first

if nextprime +n <=N %looking for non-zero
sqrt(nextprime) %if non-zero -- looking for prime

nextprime = R(nextprime+n) %update nextp

end
end
end

for n=2:length(R); %list primes only - omit "1"
if (R(n)~=0);
primeven=[primeven,R(n)] %add to existing vector of
%primes
end
end

#### MrChips

Joined Oct 2, 2009
24,625

Rich (BB code):
clear;
clc;
tic;
N=15 %largest number in list
R=linspace (1,N,N) %starting list - all numbers up to n - Matlab
%linspace calculates the space evenly between elements 1=starting value,
%N=largest value, N=total
nextprime=2 %starting with 2

if (nextprime*nextprime) <N %quit once through all numbers
end

for k=2:N %starts at 2 to start looking for prime

if nextprime*k <=N %don't exceed length of vector
R(nextprime*k) = 0 % 0 if even

end
end
% end %this is taking out all the even numbers

%trying to get prime only numbers --THIS IS WHERE MY PROBLEM IS
for n=2:N %starts at 2 to start prime ???

if R (nextprime+n) <=0 %go up list until first

if nextprime +n <=N %looking for non-zero
sqrt(nextprime) %if non-zero -- looking for prime

nextprime = R(nextprime+n) %update nextp

end
end
end

for n=2:length(R); %list primes only - omit "1"
if (R(n)~=0);
primeven=[primeven,R(n)] %add to existing vector of
%primes
end
end

#### magnet18

Joined Dec 22, 2010
1,227
jeez man, try cleaning up your code with some indents, makes things so much easier to read

why did you switch from uppercase to lowercase n?
is it a mistake, or an entirely new variable?

#### THE_RB

Joined Feb 11, 2008
5,438
You don't need a sqrt to find primes, and that's actually a very slow way to do it.