改进装配程序

时间:2015-03-18 03:37:53

标签: assembly masm factorial irvine32

我想编写一个通过参数的阶乘过程。请帮忙。帮助我看看这段代码是否需要改进,比如如何使这段代码变得更简单。这太长了,我只想要主要功能。

 INCLUDELIB C:\Irvine\Kernel32.lib
 INCLUDELIB C:\Irvine\Irvine32.lib
 INCLUDE C:\Irvine\Irvine32.inc

 .code
 main PROC
     push 5             ; calc 5!
     call Factorial     ; calculate factorial (EAX)
     call WriteDec      ; display it
     call Crlf
     exit
 main ENDP

 ;----------------------------------------------------------
 Factorial PROC
 ; Calculates a factorial.
 ; Receives: [ebp+8] = n, the number to calculate
 ; Returns: eax = the factorial of n
 ;----------------------------------------------------------
 push ebp
 mov ebp,esp
 mov eax,[ebp+8]     ; get n
 cmp eax,0                 ; n > 0?
 ja L1                ; yes: continue
 mov eax,1                 ; no: return 1 as the value of 0!
 jmp L2               ; and return to the caller

 L1: dec  eax             ; Factorial(n-1)
 push eax
 call Factorial

; Instructions from this point on execute when each
; recursive call returns.

 ReturnFact:
 mov ebx,[ebp+8]     ; get n
 mul ebx              ; EDX:EAX = EAX * EBX

 L2: pop ebp         ; return EAX
 ret 4                ; clean up stack
 Factorial ENDP
 END main

2 个答案:

答案 0 :(得分:3)

这将额外乘以1,但它很短。

factorial proc  near
        mov     ecx,[esp+4]
        mov     eax,1
        cmp     ecx,eax
        jb      fct1
fct0:   mul     ecx
        loop    fct0
fct1:   ret
factorial endp

答案 1 :(得分:0)

接下来是使用循环指令的非递归阶乘的完整程序,只需复制,粘贴和运行(用EMU8086制作):

.stack 100h
.data
my_factor dw 5
.code          
;INITIALIZE DATA SEGMENT.
  mov  ax,@data
  mov  ds,ax

  push my_factor  
  call non_recursive_factorial

;FINISH PROGRAM PROPERLY.  
  mov  ax,4c00h
  int  21h           

proc non_recursive_factorial
  pop  ax         ;EXTRACT THE ADDRESS TO RETURN TO CALL.
  pop  my_factor  ;EXTRACT THE PARAMETER (THE FACTOR).
  push ax         ;PUT BACK THE ADDRESS TO RETURN TO CALL.
  mov  ax,my_factor
  mov  cx,my_factor
  dec  cx            
while:                                  
  mul  cx ;AX*CX = DX:AX.
  loop while
  ret
endp