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.

Answers (1)

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
...

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 1 Mar 2014

Edited:

on 1 Mar 2014

Community Treasure Hunt

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

Start Hunting!