I am new to matlab and I am trying to get prime numbers
3 views (last 30 days)
Show older comments
Trying to get prime numbers but the result is giving me 5,7,9,10,11,12
for x=2:100
for y=2:100
if mod(x,y)
break
end
end
if (y<(x/y))
fprintf('%d prime',x)
end
end
0 Comments
Accepted Answer
John D'Errico
on 20 Feb 2024
Edited: John D'Errico
on 20 Feb 2024
But these loops will not result in prime numbers. (As you have found.) I think you are trying to do a simple sieve, or something like it. But this will not work, what you did. You did make an effort though.
Instead, try this:
Pmax = 100;
for n = 2:Pmax
% you only need to perform a test divide up to sqrt(n)
% but there is no need to use a loop for this. because
% mod is vectorized.
m = 2:sqrt(n);
if all(mod(n,m))
% had any of those mods generated a zero, then the
% corresponding element of m would divide n, and so
% n could not be prime. The all function merely looks
% for any zero elements, returning false if any of
% the elements are zero.
disp(n + " is prime")
end
end
This is not a true sieve. Merely test divisions using the mod function. I could have been much more efficient of course.
0 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!