Store prime and non-prime numbers

5 views (last 30 days)
Eustaquio
Eustaquio on 4 Oct 2022
Commented: Eustaquio on 4 Oct 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 Comments
Davide Masiello
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))
p = 1×15
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
np = N(~any(N==p'))
np = 1×35
1 4 6 8 9 10 12 14 15 16 18 20 21 22 24 25 26 27 28 30 32 33 34 35 36 38 39 40 42 44
Eustaquio
Eustaquio on 4 Oct 2022
Hi Davide!
Well, it is actually a seminar on Matlab for my master's course, and I want to learn basically for and while loops. Actualy, I am not using the prime function (just to make it harder for me and understanding things better).
I don't know if you saw the error on my code?
Even if you didn't, thank you so much!

Sign in to comment.

Accepted Answer

Torsten
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
p = 1×15
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
np
np = 1×35
1 4 6 8 9 10 12 14 15 16 18 20 21 22 24 25 26 27 28 30 32 33 34 35 36 38 39 40 42 44

More Answers (0)

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!