汇编-递归
递归过程是一种调用自身的过程。递归有两种:直接递归和间接递归。在直接递归中,过程调用自身;在间接递归中,第一个过程调用第二个过程,第二个过程又调用第一个过程。
在许多数学算法中都可以观察到递归。例如,考虑计算数字的阶乘的情况。数字的阶乘由以下方程给出 -
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