Nested for loop help

6 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by