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.

답변 (1개)

Mischa Kim
Mischa Kim 2014년 3월 1일
편집: Mischa Kim 2014년 3월 1일

0 개 추천

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2014년 3월 1일

편집:

2014년 3월 1일

Community Treasure Hunt

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

Start Hunting!

Translated by