Nested for loop help

6 views (last 30 days)
Ashley Sullivan
Ashley Sullivan on 9 Mar 2020
Commented: Rena Berman on 14 May 2020
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 Comments
Stephen23
Stephen23 on 11 Mar 2020
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 on 14 May 2020
(Answers Dev) Restored edit

Sign in to comment.

Accepted Answer

Ameer Hamza
Ameer Hamza on 9 Mar 2020
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);

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!