问题描述
以下是我编写的在EMU8086中查找两个数字的LCM的代码。当我运行它时,我在Ans变量中得到的值为0。
.MODEL SMALL
.DATA
Num1 DW 250
Num2 DW 100
Ans DW ?
.CODE
MOV AX,@DATA
MOV DS,AX
MOV AX,Num1
MOV BX,Num2
MOV DX,0000h
NEXT: PUSH AX
PUSH DX
DIV BX
CMP DX,0000h
JZ LAST
POP DX
POP AX
ADD AX,Num1
JNC NEXT
INC DX
JMP NEXT
LAST: POP Ans+2
POP Ans
MOV AH,4Ch
INT 21h
END
解决方法
LCM(a,b)= a * b / GCD(a,b)
由于这个方程,您可以使用欧几里得算法找到GCD,然后计算LCM。假设数字a和b在al和dl中,则此代码将计算LCM。
; Save multiplication value
MOV AL,DL ; This 2 lines is AL * DH
MUL DH
PUSH AX ; Store result in stack
FINDBCD: ; General idea is : LCM(a,b) = a*b/BCD(a,b)
; We calculate BCD with euclidean algorithm
CMP DH,DL
JNS CALCULATE ; Jump if DL < DH else swap them
MOV CL,DL ; This 3 line swap DL and DH
MOV DL,DH
MOV DH,CL
CALCULATE:
MOV AL,DH ; Move greater number in AL
XOR AH,AH ; Zero AX 8 second bits
DIV DL ; This is AL/DL
CMP AH,0 ; If remainder is zero so we found BCD
JE AFTERFINDBCD
SUB DH,DL ; Else substract smaller number from greater number
JMP FINDBCD ; Do this until find BCD
AFTERFINDBCD:
CMP DH,DL
JNS FINDLCM ; Jump if DL < DH
MOV CL,CL
FINDLCM:
POP AX ; Retreive multiplication result
DIV DL ; This is AX/DL
AND AX,0000000011111111B ; Ignore remainder