조회 수: 3(최근 30일)
Maria 19 Jun 2020
댓글: Maria 19 Jun 2020
hey ! for my code below, I think I avoid "1" for prime number, but it seems like the output still show 1 as an prime number. How should I fix it? Like if you print out [1 3 4 88 5 ], it only returns 3, 5 but here it returns 1,3,5. Can someone help to fix?
function primeVec = vecOfPrimes(vec)
k = 1;
for i=1:length(vec)
n = vec(i);
flag = 1;
for j=2:sqrt(n)
if mod(n, j) == 0
flag = 0;
break
end
end
if flag == 1
primeVec(k) = n;
k = k + 1;
end
end
end

댓글을 달려면 로그인하십시오.

### 채택된 답변

the cyclist 19 Jun 2020
The reason is that if an element of vec is equal to 1, then
for j=2:sqrt(n)
is
for j=2:1
so that for loop is never entered, and you do not flip flag to zero.
You might need to consider 1 as a special case.

#### 댓글 수: 3

Maria 19 Jun 2020
you know how to fix it? Like except 1?
the cyclist 19 Jun 2020
No offense, but it seems a little surprising to me that you know how to write the logic of the above code, but cannot then figure out this last little bit.
Is your homework to simply modify this code that was provided to you?
I'm happy to help, but if this is homework, it would be better for your learning if I give you a hint, rather than the straight-up answer.
Maria 19 Jun 2020
I got it. Thanks for clue!

댓글을 달려면 로그인하십시오.

### Community Treasure Hunt

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

Start Hunting!