The greatest common divisor (GCD) of two integers is the largest integer that wi
ID: 3775510 • Letter: T
Question
The greatest common divisor (GCD) of two integers is the largest integer that will evenly divide
both integers. The GCD algorithm involves integer division in a loop, described by the following
pseudocode:
int GCD(int x, int y)
{
x = abs(x) // absolute value
y = abs(y)
do {
int n = x % y
x = y
y = n
} while (y > 0)
return x
}
Implement this function in assembly language and write a test program that calls the function
several times, passing it different values. Display all results on the screen.
I have this codes but it doesn't work.
INCLUDE Irvine32.inc
.data
array SDWORD -5,-20,18,24,11,7,438,226,13,-26
str1 BYTE "Greatest common divisor is: ",0
.code
main PROC
mov ecx,LENGTHOF array / 2
mov esi,OFFSET array
L1: mov eax,[esi]
mov ebx,[esi+4]
call CalcGcd
mov edx,OFFSET str1
call WriteString
call WriteDec
call Crlf
add esi,TYPE array * 2
loop L1
exit
main ENDP
CalcGcd PROC
push ebx
push edx
.IF SDWORD PTR eax < 0
neg eax
.ENDIF
.IF SDWORD PTR ebx < 0
neg ebx
.ENDIF
L1: mov edx,0
div ebx
cmp edx,0
je L2 ; yes: quit
mov eax,ebx
mov ebx,edx
jmp L1
L2: mov eax,ebx
pop edx
pop ebx
ret
CalcGcd ENDP
END main
Explanation / Answer
hope this is usefull
INCLUDE Irvine32.inc
.data
array SDWORD -5,-20,18,24,11,7,438,226,13,-26
str1 BYTE "Greatest common divisor is: ",0
.code
main PROC
mov ecx,LENGTHOF array / 2
mov esi,OFFSET array
L1: mov eax,[esi]
mov ebx,[esi+4]
call CalcGcd
mov edx,OFFSET str1
call WriteString
call WriteDec
call Crlf
add esi,TYPE array * 2
loop L1
exit
main ENDP
push ebx
push edx
.IF SDWORD PTR eax < 0 ; force a signed comparison
neg eax ; EAX = abs(EAX)
.ENDIF
.IF SDWORD PTR ebx < 0
neg ebx ; EBX = abs(EBX)
.ENDIF
L1: mov edx,0
div ebx ; divide int1 by int2
cmp edx,0 ; remainder = 0?
je L2 ; yes: quit
mov eax,ebx ; no: prepare for
mov ebx,edx ; next iteration
jmp L1
L2: mov eax,ebx ; EAX = GCD
pop edx
pop ebx
ret
CalcGcd ENDP
END main
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.