Tuesday, 19 November 2013

MATLAB : Prime Number or Not

Read these books to get more advanced knowledge in MATLAB


The following code gives whether the number entered is a prime number or not :

x = input ('Input a number: ')
p=1;

for n = 2:sqrt(x)
   if x~=n && mod (x, n) == 0
    p=0;
   break
   end
end

if p == 0
    sprintf (' The input %d is NOT a prime number %d ', x)
else
    sprintf ('Input %d is a prime number', x)
end

Examples:
>> prime2
Input a number: 199

x =

   199


ans =

Input 199 is a prime number

>> prime2
Input a number: 1234567

x =

     1234567


ans =

 The input 1234567 is NOT a prime number 

No comments:

Post a Comment