prime number in assembly language 8086

Example Code 1 for prime number in assembly language 8086

.MODEL SMALL
.STACK 100H

.DATA

NUM DB ?
MSG1 DB 10,13,'ENTER NO: \$'
MSG2 DB 10,13,'NOT PRIME: \$'
MSG3 DB 10,13,'PRIME \$'

.CODE
MAIN PROC

MOV AX,@DATA
MOV DS,AX

LEA DX,MSG1
MOV AH,9
INT 21H

MOV AH,1
INT 21H
SUB AL,30H
MOV NUM,AL

CMP AL,1
JLE LBL2
MOV AH,00
CMP AL,3
JLE LBL3
MOV AH,00

MOV CL,2
DIV CL
MOV CL,AL

LBL1:

MOV AH,00
MOV AL,NUM
DIV CL
CMP AH,00
JZ LBL2
DEC CL
CMP CL,1
JNE LBL1
JMP LBL3

LBL2:

MOV AH,9
LEA DX,MSG2
INT 21H
JMP EXIT

LBL3:

MOV AH,9
LEA DX,MSG3
INT 21H

EXIT:

MOV AH,4CH
INT 21H

MAIN ENDP
END MAIN

Example Code 2 for prime number in assembly language 8086

Logic of Prime Number Check in Assembly Code
• Before going to the assembly code let me explain the programming logic first.
• Suppose the given number is ‘x’. Let us divide the number x with (x-1). I.e. x/(x-1).
• Now check the reminder status. Reminder is store in DX register b default.
• Now divide x with x-2, i.e. x/(x-2) then check the reminder.
• Repeat this step up to the denominator become 2.
• Denominator is like (x-1), (x-2),(x-3),….etc. 2
• When the reminder=0, the number is ‘Not Prime’, else it is ‘Prime’
Prime Number Program in 8086
Now let’s see the 8086 assembly language code for prime number checking. [cc lang=”C”]1000 XOR CX,CX /*Clearing the registers*/
1002 XOR DX,DX /*Clearing the registers*/
1004 MOV AX,[1500] /*Assume the number is store in memory 1500*/
1006 MOV BX,AX /*Copy the value in AX to BX */
1008 DEC BX
1010 DIV BX /*Dividing*/
1012 CMP DX,0000 /*Check for Reminder, Reminder is stored in DX*/
1014 JZ step 13
1016 XOR DX,DX /*Clearing DX*/
1018 CMP BX,0002
1020 JNZ 1008
1022 MOV CX,0001
1024 MOV [2000],CX /*Storing the result*/
1026 HLT[/cc]

Example Code 3 for prime number in assembly language 8086

Data Segment
arrprime db 20 dup (?)
i db 02h
Data Ends

Code Segment
Assume cs:code, ds:data
Begin:
mov ax, data
mov ds, ax
mov es, ax

mov dl, 01h
mov cx, 10h
lea di, arrprime

L1:
mov bl, 02

cmp dl, 02h
je Insert
cmp dl, 03h
je Insert
cmp dl, 04h
jge Logic

Logic:
mov ah, 00
mov al, dl
div bl
cmp ah, 00
je L1
cmp bl, al
jle Logic
jmp insert

Insert:
mov [di], dl
inc di
loop L1

Exit:
mov ax, 4c00h
int 21h
Code Ends
End Begin

Data Segment
arrprime db 20 dup (?)
i db 02h
Data Ends

Code Segment
Assume cs:code, ds:data
Begin:
mov ax, data
mov ds, ax
mov es, ax

mov dl, 01h
mov cx, 10h
lea di, arrprime

L1:
mov bl, 02

cmp dl, 02h
je Insert
cmp dl, 03h
je Insert
cmp dl, 04h
jge Logic

Logic:
mov ah, 00
mov al, dl
div bl
cmp ah, 00
je L1
cmp bl, al
jle Logic
jmp insert

Insert:
mov [di], dl
inc di
loop L1

Exit:
mov ax, 4c00h
int 21h
Code Ends
End Begin