MATLAB Answers

For loop checking if number is prime (without using MATLAB functions)

3 views (last 30 days)
Losoupbowla on 28 Jan 2021
Commented: Losoupbowla on 28 Jan 2021
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.
for i=2:ceil(x2/2)
if mod(x2,i) ==0
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

Accepted Answer

John D'Errico
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
ans = 1000
ans = 500000
Which loop do you want to execute?
Losoupbowla on 28 Jan 2021
I think break will do, since there were no specific rules saying not to use break. As regarding why I would test every divisor is that when prof is grading them, he actually uses a program that inputs random values at the place of x2 so we never know what will get tested.
Thank you for your help, truly appreciate it.

Sign in to comment.

More Answers (1)

Community Treasure Hunt

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

Start Hunting!