Finding Prime numbers (NO isprime function)

조회 수: 27 (최근 30일)
gmltn1212
gmltn1212 2020년 6월 13일
댓글: Walter Roberson 2020년 6월 13일
Hi, I am trying to return if the value is prime or not. And here is my code
vec = [3 4 88 5 1371];
for i = 1:length(vec)
b = mod(vec(i),2);
if vec(i)==1
disp('not prime');
elseif vec(i)==2
disp('prime');
elseif b==0
disp('not prime');
elseif b>0
for j = 3:2:(vec(i)-1)
b = mod(vec(i), j);
if b==0
disp('not prime');
end
end
disp('prime');
else
disp('not prime');
end
end
However, this code returned this
prime
not prime
not prime
prime
not prime
not prime
prime
Could you please tell me why its returning 7 outputs not 5? Also could you fix this code so it only returns 5 outputs?
  댓글 수: 2
Stephen23
Stephen23 2020년 6월 13일
편집: Stephen23 2020년 6월 13일
"Could you please tell me why its returning 7 outputs not 5?"
Look at your j-loop: within that loop your code could call disp zero, one, or more times, depending on the vec(j) value.
And then after the j-loop, you call disp once more. Your code does nothing to ensure that you only call disp once for each vec value.
"Also could you fix this code so it only returns 5 outputs?"
Get rid of the j-loop and write vectorized code. It will be simpler.
Note that you do not need to check up to vec(i)-1, up to sqrt(vec(i)) is sufficient and more efficient.
gmltn1212
gmltn1212 2020년 6월 13일
Thank you for replying to my post! However, Im having a hard time understanding your comment! It would be really helpful if you could show me how to fix it with code...

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

답변 (1개)

Walter Roberson
Walter Roberson 2020년 6월 13일
if b==0
disp('not prime');
end
You should exit the j loop as soon as you prove the number is not prime.
disp('prime');
You are doing that no matter what the outcome of your for j loop is.
  댓글 수: 2
gmltn1212
gmltn1212 2020년 6월 13일
편집: gmltn1212 2020년 6월 13일
I thought I exited after writing that code.. Could you show me how to fix this?
Walter Roberson
Walter Roberson 2020년 6월 13일
if b==0
disp('not prime');
break;
end
end
if b ~= 0
disp('prime')
end

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

카테고리

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