MATLAB Answers


Prime number or its nearest prime numbers

Asked by Rahul Singh on 13 Apr 2012

anyone please tell me in matlab how to write a function to find prime number of any number if it is not prime number then function show its nearest prime numbers... let take example ...take number 9 we know it is not prime then the program will show its nearest prime like 7 and 11..


if this is homework, can you show, what you have done so far?

What have you tried so far and which problem occurred?

Log in to comment.

2 Answers

Answer by Andrei Bobrov
on 13 Apr 2012
 Accepted Answer

input x

x = 24;


X = [x x];
out = zeros(1,2);
while 1
   t = isprime(X);
   if all(t)
       out = X;
   elseif any(t)
       out(t) = X(t);
       t1 = ~t;
       X(t1) = X(t1) - sum([1 -1].*t1);
       X = X - [1 -1];
out = unique(X)


I assume, this is the solution of Rahul's homework, Andrei.

thanks Andrei Bobrov........i think this is useful answer for me............

Log in to comment.

Answer by Sean de Wolski
on 13 Apr 2012

isprime() will be your friend.


Log in to comment.

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Win prizes and improve your MATLAB skills

Play today