Greatest common divisor (GCD) of two numbers
A program that finds the greatest common divisor (GCD) of two numbers using the Euclidean algorithm.
Program source code
title .model small .stack 100h data segment public askUser db "Enter two numbers: \0" fmtoutput db "\nGreatest common divisor is: %d\0" fmtinput db "%d %d" firstNumber dw ? secondNumber dw ? data ends code segment public ; Start of the code segment assume ds:data, cs:code include Handyfar.inc ; Include the file with functions main proc ; Start of the main procedure call SetDataSegment ; Call the SetDataSegment procedure lea ax, ds:[askUser] ; Load the address of the askUser variable into ax call WriteString ; Call the WriteString procedure lea ax, ds:[secondNumber] ; Load the address of the secondNumber variable into the ax register push ax ; 3rd: save the ax register value on the stack lea ax, ds:[firstNumber] ; Load the address of the firstNumber variable into the ax register push ax ; 2nd: save the ax register value on the stack lea ax, ds:[fmtinput] ; 1st: load the address of the fmtinput format string into ax call ScanFormatString ; Call the ScanFormatString procedure add sp, 4 ; Align the stack push secondNumber ; 2nd: save the secondNumber variable value on the stack push firstNumber ; 1st: save the firstNumber variable value on the stack call GCD ; Call the GCD procedure push ax ; 2nd: save the ax register value on the stack lea ax, ds:[fmtoutput] ; 1st: load the address of the fmtoutput format string into the ax register call PrintFormatString ; Call the PrintFormatString procedure add sp, 2 ; Align the stack xor al, al ; Clear the al register call ExitProcess ; Call the ExitProcess procedure main endp ; End of the main procedure GCD proc ; Start of the GCD procedure push bp ; Save the bp register value on the stack mov bp, sp ; Copy the sp register value into bp cmp word ptr[bp+4], 0 ; Check firstNumber for 0 jz Finish ; If firstNumber is 0, jump to the Finish label cmp word ptr[bp+6], 0 ; Check secondNumber for 0 jz Finish ; If secondNumber is 0, jump to the Finish label mov bx, word ptr[bp+6] ; Copy secondNumber into the bx register MainLoop: xor dx, dx ; Clear the dx register mov ax, word ptr[bp+4] ; Copy firstNumber into the ax register div bx ; Divide firstNumber by secondNumber mov word ptr[bp+4], bx ; Copy the bx register into firstNumber mov bx, dx ; Copy the remainder into the bx register cmp dx, 0 ; Check the remainder for 0 jnz MainLoop ; Loop while the remainder is not 0 mov ax, word ptr[bp+4] ; Copy firstNumber into the ax register Finish: pop bp ; Restore the bp register value ret 4 ; Return from the procedure, aligning the stack by 4 bytes GCD endp ; End of the GCD procedure code ends ; End of the code segment end main ; End of file. The main procedure is the entry point
Enter two numbers: 56 78
Greatest common divisor is: 2
Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".