Why is a nested loop necessary in this code?

I am having a hard time trying to decipher the usage of multiple loops in this code:
for i=2:100
for j=2:100
if(~mod(i,j))
break; % if factor found, not prime
end
end
if(j > (i/j))
fprintf('%d is prime\n', i);
end
end
I don't understand why solely one for loop wouldn't work.

Risposte (1)

Mischa Kim
Mischa Kim il 1 Mar 2014
Modificato: Mischa Kim il 1 Mar 2014
Ashkhan, the outer (first) loop is used to step through all the numbers that are analyzed. To identify a prime number you need to check if that number is divisible by any other number than itself and 1. To do so you devide each number investigated, let's call it n, by numbers ranging from 2 to n-1. This is done in the inner loop. To make the above code more efficient you would
for i = 2:100
for j = 2:(i-1) % i being the number analyzed
...

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Richiesto:

il 1 Mar 2014

Modificato:

il 1 Mar 2014

Community Treasure Hunt

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

Start Hunting!

Translated by