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
2014 年 3 月 1 日
編集済み: Mischa Kim
2014 年 3 月 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
...
カテゴリ
ヘルプ センター および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!