For loop checking if number is prime (without using MATLAB functions)
Ältere Kommentare anzeigen
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
Akzeptierte Antwort
Weitere Antworten (1)
John Wirzburger
am 28 Jan. 2021
0 Stimmen
It appears that it has to do with when you set y2. In short, you are only reporting back the y2 value when i=ceil(x2/2).
1 Kommentar
Losoupbowla
am 28 Jan. 2021
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!