write a computer program that finds all the isolated primes between 50 and 100. Do not use MATLAB's built in function isprime.

15 views (last 30 days)
Here is what I started with to find the prime numbers
for a=50:100
if rem(a,2:a/2)~=0
disp(a)
end
end
I edited my code to look like this and I am getting no answers. I am a bit lost as to why it is not working.
for a=50:100;
if rem(a,2:a/2)~=0;
b=a+2;
c=a-2;
if rem(b,2:b/2)==0;
if rem(c,2:c/2)==0;
disp(a)
end
end
end
end

Answers (1)

Stephen23
Stephen23 on 10 Mar 2018
Edited: Stephen23 on 10 Mar 2018
While if does accept vectors for the condition, using vectors often causes problems like this. When the if condition is a vector then all of its elements must be true for the if to execute the code inside the if. In the first usage you were lucky:
if rem(a,2:a/2)~=0;
this works because for prime numbers all of them a remainder zero. But in your other usages, e.g.
if rem(b,2:b/2)==0;
it will not be the case that all of the elements of that condition vector would be true, therefore those if never execute the code inside them.
The if help explains it thus: "An expression is true when its result is nonempty and contains only nonzero elements...": is this the case when you are trying to detect the b and c values? No, it is not, because some of the elements will be false.
The solution is simple: always write an explicit all or any when using a vector with if, because it makes the intention clear, and avoids bugs like this (and it will fix your bug, when pick the correct one). I would recommend that you do not use two nested if's: just use one if with a logical &&:
if ... && ...
disp(...)
end
  3 Comments

Sign in to comment.

Categories

Find more on Loops and Conditional Statements 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!