I am new to matlab and I am trying to get prime numbers
조회 수: 3 (최근 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!