Nested for loop help

5 ビュー (過去 30 日間)
Ashley Sullivan
Ashley Sullivan 2020 年 3 月 9 日
コメント済み: Rena Berman 2020 年 5 月 14 日
I'm trying to make a nested for loop to find prime numbers between 1 and 1000000 but I'm pretty sure I'm doing it wrong/got it stuck in an infinite loop because it's taking very long.
clear all
close all
primes = [ ];
tic
j=1
for m = 1:1000000 % outer loop
if isprime(m) == 1 % inner loop
primes(j) = m
j = j + 1;
m = m + 1;
else
end
m = m + 1;
end
toc
  2 件のコメント
Stephen23
Stephen23 2020 年 3 月 11 日
Original question: "Nested for loop help"
I'm trying to make a nested for loop to find prime numbers between 1 and 1000000 but I'm pretty sure I'm doing it wrong/got it stuck in an infinite loop because it's taking very long.
clear all
close all
primes = [ ];
tic
j=1
for m = 1:1000000 % outer loop
if isprime(m) == 1 % inner loop
primes(j) = m
j = j + 1;
m = m + 1;
else
end
m = m + 1;
end
toc
Rena Berman
Rena Berman 2020 年 5 月 14 日
(Answers Dev) Restored edit

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

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 3 月 9 日
Your logic is correct. However, in MATLAB, you don't need to increment the loop variable yourself, for the loop will automatically increment it. Apart from that, there is no infinite loop, it just takes a long time to complete
clear all;
close all;
primes_num = []; % name is changed because primes is also name of MATLAB built-in function
tic
j=1;
for m = 1:1000000 % outer loop
if isprime(m) == 1 % inner loop
primes_num(j) = m;
j = j + 1;
end
end
toc
You can also get the same answer using MATLAB built-in function
primes_num = primes(1000000);

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by