目录

汇编 - 递归

递归过程就是自称过程。 有两种递归:直接和间接。 在直接递归中,过程调用自身并在间接递归中,第一个过程调用第二个过程,该过程又调用第一个过程。

可以在许多数学算法中观察到递归。 例如,考虑计算数字的阶乘的情况。 一个数的因子由等式给出 -

Fact (n) = n * fact (n-1) for n > 0

例如:5的阶乘是1 x 2 x 3 x 4 x 5 = 5 x阶乘4,这可以是显示递归过程的一个很好的例子。 每个递归算法必须具有结束条件,即,当满足条件时应该停止程序的递归调用。 在阶乘算法的情况下,当n为0时达到结束条件。

以下程序显示了如何使用汇编语言实现factorial n。 为了简化程序,我们将计算阶乘3。

section	.text
   global _start         ;must be declared for using gcc
_start:                  ;tell linker entry point
   mov bx, 3             ;for calculating factorial 3
   call  proc_fact
   add   ax, 30h
   mov  [fact], ax
   mov	  edx,len        ;message length
   mov	  ecx,msg        ;message to write
   mov	  ebx,1          ;file descriptor (stdout)
   mov	  eax,4          ;system call number (sys_write)
   int	  0x80           ;call kernel
   mov   edx,1            ;message length
   mov	  ecx,fact       ;message to write
   mov	  ebx,1          ;file descriptor (stdout)
   mov	  eax,4          ;system call number (sys_write)
   int	  0x80           ;call kernel
   mov	  eax,1          ;system call number (sys_exit)
   int	  0x80           ;call kernel
proc_fact:
   cmp   bl, 1
   jg    do_calculation
   mov   ax, 1
   ret
do_calculation:
   dec   bl
   call  proc_fact
   inc   bl
   mul   bl        ;ax = al * bl
   ret
section	.data
msg db 'Factorial 3 is:',0xa	
len equ $ - msg			
section .bss
fact resb 1

编译并执行上述代码时,会产生以下结果 -

Factorial 3 is:
6
↑回到顶部↑
WIKI教程 @2018