; GCD Greatest Common Denominator ; bx = GCD(cx, dx) ; ; Input parameters: cx, dx ; Return value: bx ; ; The greatest common denominator (GCD) is the largest positive integer ; that divides into both numbers without a remainder. ; Examples: GCD(256,64)=64, GCD(12,8)=4, GCD(5,3)=1 GCD PROC ; Work with absolute values ; Require cx>=0 and dx>=0 ; Ensure cx >= 0 cmp cx, 0 jge cx_ok ; cx < 0, swap cx = -cx mov ax, 0 sub ax, cx mov cx, ax cx_ok: ; Ensure dx >= 0 cmp dx, 0 jge dx_ok ; dx < 0, swap dx = -dx mov ax, 0 sub ax, dx mov dx, ax dx_ok: ; Check for cx = dx = 0 cmp cx, 0 jnz calculate_gcd cmp dx, 0 jnz calculate_gcd ; Error, both parameters cx = dx = 0 ; Return value bx=0 mov bx, 0 ret calculate_gcd: ; Calculate GCD(cx, dx) ; Store interim result in bx ; Set initial GCD value mov bx, cx ; Iterate until dx = 0 gcd_loop: cmp dx, 0 jz gcd_done mov bx, dx ; Store interim result in bx ; Swap registers for div: ; ax=cx, cx=dx, dx=0 mov ax, cx mov cx, dx mov dx, 0 ; dx = dx:ax modulo cx div cx ; cx = bx (for next iteration) mov cx, bx jmp gcd_loop gcd_done: ; OK, done ; Return with bx = GCD ret GCD ENDP
Hide code
Visustin flow chart for MASM