Prime Numbers | MATLAB Tutorial

Prime Numbers | MATLAB Tutorial

Checking whether a number is Prime or a composite number using MATLAB

What is a prime number?

  • It is a number which is only divisible by 1 and itself.
  • It should not be divisible by any other number.If it is divisible by another number then it is called a composite number.

Example for prime numbers are  :- 2, 3, 5, 7, 11, 13 etc.

Example for composite numbers are:- 4, 6, 8, 9, 10, 12, 14, 15, 16 and so on.


a =input('Enter your Number');
for i=2:a/2
if mod(a,i)==0
if flag==0
fprintf('%d is a prime number',a)
fprintf('%d is not a prime number',a)


  • The user is asked to enter a number to check whether it is a prime number or a composite number.
  • The input number by the user is then divided by every number ranging between the  2 to the half of the number entered by the user and then if the remainder of any division between that range results in ‘0’ then the flag variable is made to be ‘1’ and then this flag indicates that the number entered by the user is a composite number.
  • Else if the flag is still ‘0’ then the number is a prime number.

Below you can see the output image for various numbers given as input to the code in matlab.


I am currently pursuing my btech in Electronics and communication engineering from Amrita Vishwa Vidyapeetham. My areas of interest are signal processing, Communication systems, Control system.