I am new to matlab and I am trying to get prime numbers
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
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")
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 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!