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.

Respuestas (1)

Mischa Kim
Mischa Kim el 1 de Mzo. de 2014
Editada: Mischa Kim el 1 de Mzo. de 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
...

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Etiquetas

Preguntada:

el 1 de Mzo. de 2014

Editada:

el 1 de Mzo. de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by