In this blog post, we’ll explore an 8086 assembly program that computes the Greatest Common Divisor (GCD) of two numbers using the classic Euclidean Algorithm.
The Euclidean method is an efficient and elegant way to find the largest number that divides both inputs without leaving a remainder.
The principle is simple:
GCD(A, B) = GCD(B, A mod B)
This process repeats until the remainder becomes zero. At that point, the divisor is the GCD.
Let’s dive into the code and understand how it works!
Program Code
data segment
a dw 0012h ; First number (18 decimal)
b dw 000Ah ; Second number (10 decimal)
gcd_result dw ? ; Variable to store the GCD
data ends
code segment
assume cs:code, ds:data
start:
mov ax, data
mov ds, ax ; Initialize data segment
mov ax, a ; Load A into AX
mov bx, b ; Load B into BX
cmp bx, 0000h ; Check if B is zero
jz store_result
gcd_loop:
mov dx, 0000h ; Clear DX before division
div bx ; AX = AX / BX, remainder in DX
cmp dx, 0000h ; If remainder = 0, GCD found
je store_result_bx
mov ax, bx ; A = B
mov bx, dx ; B = remainder
jmp gcd_loop ; Repeat loop
store_result_bx:
mov ax, bx ; Move GCD into AX
store_result:
mov gcd_result, ax ; Store final result
int 3 ; Stop execution
code ends
end start