Store prime and non-prime numbers
5 views (last 30 days)
Show older comments
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 Comments
Davide Masiello
on 4 Oct 2022
Edited: Davide Masiello
on 4 Oct 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'))
Accepted Answer
Torsten
on 4 Oct 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
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!