MATLAB Answers

# I need a program to check prime numbers

540 views (last 30 days)
Toni Clares on 8 Oct 2016
Edited: Asastra on 13 Jun 2020
%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.

### Accepted Answer

Andrei Bobrov on 8 Oct 2016
Edited: Andrei Bobrov on 8 Oct 2016
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.

### More Answers (3)

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

Walter Roberson on 21 Jul 2019
After C=0 it would make sense to break the for loop.

Sign in to comment.

koushik roy on 20 Sep 2019
clc
clear all
num=31;
a=primes(num);
prm=a((length(a)));
if num==prm
out=num; % If the number is prime
end

#### 1 Comment

Walter Roberson on 20 Sep 2019
Note that a(length(a)) would be the same as a(end) in the case of vector a
Your code does not define out if num==prm is false.
Your code appears to be operating by checking whether primes(num) ends in num . But if you are permitted to use primes() then just use isprime(num) instead of going to that work.

Sign in to comment.

Asastra on 12 Jun 2020
Edited: Asastra on 13 Jun 2020
Old question but still interesting.
I made this code and compared it to isprime. I found that it is faster than isprime for quite a large number ( I do knot for a very large number).
It is interesting to know what algorithm is used by "isprime" built in function.
=====
clear all
clc
n=100000007 %number to check
%this for built-in isprime
tic
a = isprime(n);
if a==1
disp('prime')
else
disp('not prime')
end
toc
%this for alternative code
%a function to decide a number is prime or not
tic
b= isPrime(n);
if b==1
disp('prime')
else
disp('not prime')
end
toc
%this is the function of isPrime
function isprima = isPrime(n)
b = mod(n,2);
if n==1 || n==-1
isprima=0;
elseif n==2 || n==-2
isprima=1;
elseif b==0
isprima=0;
elseif b>0
for m = 3:2:sqrt(abs(n)) %instead of i = 3:2:(n-1)
b = mod(n,m);
if b==0
isprima=0;
return
end
end
isprima=1;
endif

#### 0 Comments

Sign in to comment.