Question

INCLUDE Irvine32.inc

.data   
        heading     BYTE    "This is a program for GCD.........", 0
        inputX      BYTE    "Enter an integer X: ", 0
        inputY      BYTE    "Enter an integer Y: ", 0
        ansGCD      BYTE    "The value of GCD is: ", 0
        valX        DWORD   ?
        valY        DWORD   ?       

.code
main PROC       
        mov edx, OFFSET heading         ;print header
        call WriteString
        call Crlf

        mov edx, OFFSET inputX          ;input X
        call WriteString
        call ReadDec
        mov valX, eax
        call Crlf

        mov edx, OFFSET inputY          ;inputY
        call WriteString
        call ReadDec
        mov valY, eax
        call Crlf

        mov eax,DWORD ptr[valX]     ;dividend
        mov ebx,DWORD ptr[valY]     ;divisor
        push valY                       ;pushing values into stack
        push valX
        call CalcGdcI
        call Dumpregs

        exit
main ENDP


CalcGdcI PROC
        xor edx, edx
        mov eax, DWORD ptr[esp+8]       ;dividend
        mov ebx, DWORD ptr[esp+4]       ;divisor
        div ebx                         ;eax/ebx
        cmp edx, 0                      ;remainder in edx
        je L1                           ;yes: quit
        call CalcGdcI                   ;no: call CalcGdcI again
L1:
        mov eax, ebx                    ;move the divisor into eax to print
        mov edx, OFFSET ansGCD
        call WriteString
        call WriteDec                   ;Display GCD WriteInt
        call Crlf
        ret 8                           ;clean up the stack
CalcGdcI ENDP

END main

i'm getting wrong answer if the number is not exactly divisible, like for (54,24) but works fine with like, (10,100)...thanks

Was it helpful?

Solution

I think you should write something like (I have wrote assembly for years):

CalcGdcI PROC
    xor edx, edx
    mov eax, DWORD ptr[esp+8]       ;dividend
    mov ebx, DWORD ptr[esp+4]       ;divisor
loop:
    div ebx                         ;eax/ebx
    cmp edx, 0                      ;remainder in edx
    je L1                           ;yes: quit
    mov eax, ebx                    ;restart with eax = ebx
    mov ebx, edx                    ;and          ebx = edx
    jmp loop
l1: 
    ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top