您的位置:首页 > 其它

求最大公约数和最小公倍数

2010-03-10 15:11 253 查看
很无聊做些无聊的事。

使用MASM开发,经过测试

题目: 0<m,n <2^32 求最大公约数和最小公倍数

1 使用辗转相除法求最大公约数。

GreatestCommDivisor PROC USES ebx ecx edx esi edi, m : DWORD ,n : DWORD

mov eax,m

mov ebx,n

fun_start:

cmp eax,ebx

jae no_exchange

;exchange the m,n . m<->n

xchg eax,ebx

no_exchange:

test ebx,ebx

jz error ; goto exit

cdq ;eax ->edx:eax

div ebx ; eax = m/n edx = m % n

test edx,edx ; is zero ?

jz exit ;ok ,the result is edx.

mov eax,ebx

mov ebx,edx

jmp fun_start

error:

mov eax,0

ret

exit:

mov eax,ebx

ret

GreatestCommDivisor endp

2 利用求得的最大公约数 g, 用 p=m/g ,q=n/g result = p*q*g

LeaseCommonMultiple PROC USES ebx ecx edx esi, m : DWORD,n :DWORD

Invoke GreatestCommDivisor,m,n

;save greatest common divisor to ebx

mov ebx,eax

mov eax,m

cdq

div ebx

mov esi,eax ;save quotient to esi

mov eax,n

cdq

div ebx ; the result is in eax

;mov ecx,eax ; sava n/g -> ecx

;;;;;;;;;;;;;;;;;;;;;;;;;;

;result = esi*ecx*g; 'g' --- Greatest common divisor

;;;;;;;;;;;;;;;;;;;;;;;;;

mul esi

mul ebx

ret

LeaseCommonMultiple endp
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: