Calculating prime numbers using mod

1 回表示 (過去 30 日間)
Jose Trevino
Jose Trevino 2016 年 2 月 15 日
コメント済み: Jose Trevino 2016 年 2 月 15 日
Hi, I have a code that its supposed to calculate all prime numbers from an input of n numbers. However, in the first loop, the code uses "mod" to check if the number is divisible by any number from 2 to sqrt of n and after dividing by 2 it does not proceed to 3 and discard multiples of 3, 5 and so for. How can I fix this issue?
n = 20;
L = 2:n;
index = 2;
for k = 2:floor(sqrt(n))
while index < n
if (mod(L(index),k) == 0)
L(index) = 0;
end
index = index + 1;
end
end
L';
Prime=L(L~=0);
Prime'

回答 (1 件)

Walter Roberson
Walter Roberson 2016 年 2 月 15 日
You need to reset index at the beginning of the for loop.
  1 件のコメント
Jose Trevino
Jose Trevino 2016 年 2 月 15 日
how do I do that? That's what I was trying with no luck

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by