3 views (last 30 days)

Show older comments

This is my code. Task is to check if x2 is prime. If yes, set y2 to be logical one and if no, set y2 to be logical zero. We are not allowed to use pre-made functions.

x2=22;

for i=2:ceil(x2/2)

if mod(x2,i) ==0

y2=false;

else

y2=true;

end

end

My code runs and seems to work well for all numbers beside x2=99. For this input, it is giving me logical one as a result. Why and how to fix it?

Thanks in advance

John D'Errico
on 28 Jan 2021

Edited: John D'Errico
on 28 Jan 2021

Your code does NOT work well. In fact, it has a serious bug in it.

You are using a loop. EVERY pass through the loop, it sets y2 to be either true or false. So if the final pass through the loop, you just happen to get the result that mod(x2,i) == 0 or not, then your code will fail.

Instead, if ANY of those mods is zero, then you are done. There is no need to test any further, as the number cannot be prime. So you can use break to exit the loop as soon as that happens. Or you can use a while loop.

Next, you should recognize that going all the way out to x2/2 is far too long of a loop. Do you need to go past sqrt(x2)? THINK ABOUT IT!

Consider the difference between

sqrt(1e6)

1e6/2

Which loop do you want to execute?

John Wirzburger
on 28 Jan 2021

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

Start Hunting!