I am new to matlab and I am trying to get prime numbers

3 visualizzazioni (ultimi 30 giorni)
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)
if (y<(x/y))
fprintf('%d prime',x)
5 prime7 prime9 prime10 prime11 prime13 prime14 prime15 prime16 prime17 prime18 prime19 prime20 prime21 prime22 prime23 prime25 prime26 prime27 prime28 prime29 prime30 prime31 prime32 prime33 prime34 prime35 prime36 prime37 prime38 prime39 prime40 prime41 prime42 prime43 prime44 prime45 prime46 prime47 prime48 prime49 prime50 prime51 prime52 prime53 prime54 prime55 prime56 prime57 prime58 prime59 prime60 prime61 prime62 prime63 prime64 prime65 prime66 prime67 prime68 prime69 prime70 prime71 prime72 prime73 prime74 prime75 prime76 prime77 prime78 prime79 prime80 prime81 prime82 prime83 prime84 prime85 prime86 prime87 prime88 prime89 prime90 prime91 prime92 prime93 prime94 prime95 prime96 prime97 prime98 prime99 prime100 prime

Risposta accettata

John D'Errico
John D'Errico il 20 Feb 2024
Modificato: John D'Errico il 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")
2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime
This is not a true sieve. Merely test divisions using the mod function. I could have been much more efficient of course.

Più risposte (0)


Scopri di più su Loops and Conditional Statements in Help Center e File Exchange



Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by