8051 code to check whether the number is prime or not...!!

8051 Program to check whether the given number is prime or not.

What is a prime number?

Prime number is a number which divides by 1 and itself.So when we are taking in the program we have to take and check for the numbers
which are not divisible by the half of the number to be checked as a prime number.
eg: If we are checking for 11 as a prime number then it should not be divisible by numbers from 2 to 5(11/2).


1)Store the number to be checked as a prime number in the register R2.
2)Divide the number by 2 and store it in the register R0.
3)Check whether the R0 is 1 if it is one then it is a primenumber.
4)If R0 is not 1 then go on dividing the prime number with all the numbers till R0 is 1(By decrementing R0 by 1).
5)Then check if R0 is 1.If it is 1 then set the carry flag to 1 indicating that it is a prime number.
6)Suppose if the remainder dividing R2 by any number is zero then set the carry falg to 0 indicating it is not a prime number.

In this program let's learn how to check whether the number is prime or not.......!!!

Code goes here

ORG 0000h
ORG 40h
MAIN:    MOV R2,#11          ; Loading the number to be checked whether it's a prime or not
         MOV B,#02  
         DIV AB              ;Dividing the number by 2
         MOV R0,A
         CJNE R0,#01H,LABEL2 ;Checking whether the number is 2
         SETB C
         SJMP LABEL4
LABEL1:  DEC R0              ; decrementing and checking whether the number is not divisible by all possible values of number/2
         CJNE R0,#01H,LABEL2
         SETB C              ; setting the carry flag to 1 if it is a prime number
         SJMP LABEL4
         MOV B,R0
         DIV AB
         MOV R3,B
         CJNE R3,#0H,LABEL1
         CLR C              ; setting the carry falg to 0 if it not a prime number

No comments:

Powered by Blogger.