Store prime and non-prime numbers
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Eustaquio
am 4 Okt. 2022
Kommentiert: Eustaquio
am 4 Okt. 2022
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 Kommentare
Davide Masiello
am 4 Okt. 2022
Bearbeitet: Davide Masiello
am 4 Okt. 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'))
Akzeptierte Antwort
Torsten
am 4 Okt. 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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!