Prime Numbers | MATLAB Tutorial
by SAURAB S
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'); flag=0; for i=2:a/2 if mod(a,i)==0 flag=1; break; end end if flag==0 fprintf('%d is a prime number',a) else fprintf('%d is not a prime number',a) end
- 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.