MATLAB Answers

0

I need a program to check prime numbers

Asked by Toni Clares on 8 Oct 2016
Latest activity Commented on by Walter Roberson
on 21 Jul 2019
%that is my programa and it doesn't work
clc
clear all
n=input('number') % Natural number that you want to know if it a prime number
i=2;
while i<=sqrt(n)
if n==0 | n==1
disp('not prime number');
elseif rem(n,i)==0
disp(n)
disp('is prime number');
break
end
i=i+1;
end

  0 Comments

Sign in to comment.

2 Answers

Answer by Andrei Bobrov
on 8 Oct 2016
Edited by Andrei Bobrov
on 8 Oct 2016
 Accepted Answer

out = n((n(:) == 2 | rem(n(:),2)) ...
& any(rem(n(:)./([2,3:2:sqrt(max(n))]),1) ~= 0,2));
use
>> n = [2 78 53 18 97 6];
>> out = n((n(:) == 2 | rem(n(:),2)) ...
& any(rem(n(:)./([2,3:2:sqrt(max(n))]),1) ~= 0,2))
out =
2 53 97
>>

  0 Comments

Sign in to comment.


Answer by Irfan Turk on 21 Jul 2019

%This code find all prime numbers
%upto the entered number
clear all;
N=input('Prime Numbers until:');
if N<2
return;
elseif N==2
disp(2);
return;
end
Pr(1)=2;Pr(2)=3;Count=3;
for i=4:N
C=Check(i);
if C==1
Pr(Count)=i;
Count = Count +1;
end
end
disp(Pr);
function C=Check(i)
C=1;
for k=2:(ceil(sqrt(i)))
if mod(i,k)==0
C=0;
end
end
end

  1 Comment

After C=0 it would make sense to break the for loop.

Sign in to comment.