# Nested for loop help

조회 수: 5(최근 30일)
Ashley Sullivan 9 Mar 2020
댓글: Rena Berman 14 May 2020 16:41
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

Stephen Cobeldick 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 14 May 2020 16:41

로그인 to comment.

### 채택된 답변

Ameer Hamza 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);

로그인 to comment.

### 추가 답변(0개)

이 질문에 답변하려면 로그인을(를) 수행하십시오.

Translated by