汇编 - 递归



递归过程是指调用自身的过程。递归分为两种:直接和间接。直接递归中,过程调用自身,间接递归中,第一个过程调用第二个过程,而第二个过程又调用第一个过程。

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

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

例如:5 的阶乘为 1 x 2 x 3 x 4 x 5 = 5 x 4 的阶乘,这可以很好地展示一个递归过程。每个递归算法必须有一个终止条件,即当某个条件满足时,程序的递归调用应该停止。对于阶乘算法,当 n 为 0 时达到终止条件。

以下程序展示了如何在汇编语言中实现 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
广告
© . All rights reserved.