Open In App

8086 program to find GCD of two numbers and print the GCD

Improve
Improve
Like Article
Like
Save
Share
Report

Problem: We are given two decimal numbers we have to find the GCD of two numbers and print the GCD in decimal format.
Refer for finding GCD of two numbers.

Examples: 

Input: d1 = 16, d2 = 24
Output: GCD = 8

Input: d1 = 12, d2 = 18
Output: GCD = 6 

Explanation: 

  1. Load value d1 in ax and d2 in bx
  2. Call the gcd function
  3. If value in bx is zero
  4. Then set the value of gcd ( CX ) as ax
  5. Else set the value of ax as bx and value of bx as ax % bx
  6. Call the gcd function recursively
  7. Load the value of cx into ax
  8. Call the print function to print the gcd of two numbers

Program: 




.MODEL SMALL
    .STACK 100H
    .DATA
        d1 dw 16 d2 dw 24
    .CODE
        MAIN PROC FAR
            MOV AX,
    @DATA
        MOV DS,
    AX
  
;initialize ax and bx
    mov bx,
    d2
        mov ax,
    d1
  
;find gcd of two numbers
    call gcd
  
;load the gcd in ax
    mov ax,
    cx
  
;print the value
    CALL PRINT
  
;interrupt to exit
    MOV AH,
    4CH INT 21H
  
    MAIN ENDP
        GCD PROC
  
;if
    bx is 0 cmp bx, 0 jne continue
  
;then gcd is ax
    mov cx,
    ax
        ret
  
    continue:
  
;else gcd(b, a % b)
    xor dx,
    dx
  
;divide ax by bx
    div bx
  
;initialize ax as bx
    mov ax,
    bx
  
;and 
bx as ax % bx
    mov bx,
    dx
  
;recursively call gcd
    call GCD
        ret
            GCD ENDP
                PRINT PROC
  
;initialize count
    mov cx,
    0 mov dx, 0 label1:
  
;if
    ax is zero
        cmp ax,
        0 je print1
  
   
;initialize bx to 10 mov bx, 10
  
;extract the last digit
    div bx
  
;push it in the stack
    push dx
  
;increment the count
    inc cx
  
;set dx to 0
    xor dx,
    dx
        jmp label1
            print1:
  
;check if count
;is greater than zero
    cmp cx,
    0 je exit
  
;pop the top of stack
    pop dx
  
;add 48 so that it
;represents the ASCII
;value of digits
    add dx,
    48
  
;interrupt to print a
;character
    mov ah,
    02h int 21h
  
;decrease the count
    dec cx
        jmp print1
            exit : ret
                       PRINT ENDP
                           END MAIN


Output: 

8

Note: The program cannot be run on an online editor, please use MASM to run the program and use dos box to run MASM, you might use any 8086 emulator to run the program
 



Last Updated : 03 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads