[Assembly]GCD

Posted by John on 2016-06-22
Words 368 and Reading Time 2 Minutes
Viewed Times

GCD,最大公因數(Greatest Common Divisor,簡寫為G.C.D.;或Highest Common Factor,簡寫為H.C.F.),指某幾個整數共有因數中最大的一個。

介紹: 維基百科

想法: 從C/C++程式碼轉換成組合語言。

迴圈版本

INCLUDE Irvine32.inc
.data
myMessage BYTE "Please enter two integer number.",0dh,0ah,0
intVal1 SDWORD ?
intVal2 SDWORD ?
.code
main PROC
call Clrscr
mov edx,OFFSET myMessage
call WriteString


call ReadInt
mov intVal1,eax
cdq ;abs
xor eax , edx ;abs
sub eax , edx ;abs
mov ebx , eax

call ReadInt
mov intVal1,eax
cdq ;abs
xor eax , edx ;abs
sub eax , edx ;abs
mov ecx , eax

call GCD
call WriteInt
exit
main ENDP
;---------------------------------------------------------
GCD PROC
; Yo this func can help U to find the GCD from two Integer
; Receives: intVal1 in ebx , intVal2 in ecx
; Returns: GCD in eax
;---------------------------------------------------------
mov eax , ebx
L1: cdq
idiv ecx
mov eax , ecx
mov ecx , edx
cmp ecx , 0
jg L1
ret
GCD ENDP
END main

遞迴版本

INCLUDE Irvine32.inc
.data
myMessage BYTE "Please enter two integer number.",0dh,0ah,0
intVal1 SDWORD ?
intVal2 SDWORD ?
.code
main PROC
call Clrscr
mov ecx , 5
L1:
mov edx,OFFSET myMessage
call WriteString



call ReadInt
mov intVal1,eax
cdq ;abs
xor eax , edx ;abs
sub eax , edx ;abs
push eax

call ReadInt
mov intVal1,eax
cdq ;abs
xor eax , edx ;abs
sub eax , edx ;abs
push eax

call GCD
call WriteInt
call CrLf
Loop L1

exit
main ENDP
;---------------------------------------------------------
GCD PROC
; Yo this func can help U to find the GCD from two Integer Implentnt by Recursion
;
; int gcd(int m, int n) {
; if(n == 0)
; return m;
; else
; return gcd(n, m % n);
; }
;
; Receives: intVal1 in ebx , intVal2 in ecx
; Returns: GCD in eax
;---------------------------------------------------------
push ebp
mov ebp , esp

mov eax , [ebp+8] ;n
cmp eax,0 ; if n == 0
ja L1
mov eax , [ebp+12] ;m
je Quit

L1:
mov eax , [ebp+12]
cdq
mov ebx , [ebp+8]
idiv ebx
push [ebp+8] ; n
push edx ; m % n
call GCD

Return:

Quit:
pop ebp
ret 8
GCD ENDP
END main

>