I am new to matlab and I am trying to get prime numbers
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
John D'Errico
2024-2-20
编辑:John D'Errico
2024-2-20
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!