Store prime and non-prime numbers
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Hi guys! I am trying to determine and store prime and non-prime numbers from 1 to 50.
I have made a programm with a FOR and WHILE loop. However, the programm does not store the values correctly.
I don't know if you could tell where the error is and then solve it.
Thanks!
x=[1:50];
x=x';
jj=0; %index for prime_num
nn=0; %index for nonprime_num
ii=2;
p=[];
np=[];
for i=1:length(x)
while ii<=sqrt(x(i))
if rem(x(i),ii)==0
jj=jj+1;
p(jj)=x(i);
else
nn=nn+1;
np(nn)=x(i);
end
ii=ii+1;
end
end
2 Commenti
Davide Masiello
il 4 Ott 2022
Modificato: Davide Masiello
il 4 Ott 2022
Could you explain your code in more detail? It seems overly complicated, you could easily do this
N = 1:50;
p = primes(N(end))
np = N(~any(N==p'))
Risposta accettata
Torsten
il 4 Ott 2022
x=[1:50];
x=x';
jj=0; %index for prime_num
nn=1; %index for nonprime_num
p=[];
np=[];
np(1) = 1;
for i=2:length(x)
iprime = 1;
for ii=2:i/2
if mod(x(i),ii)==0
nn=nn+1;
np(nn) = x(i);
iprime = 0;
break
end
end
if iprime == 1
jj = jj+1;
p(jj) = x(i);
end
end
p
np
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Logical 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!