; Windows Assembly Language Programming Tutorial p170 Exercise 7:
The use of recursive subroutines to show the Fibonacci series, the FN of the Fibonacci series is defined as: f0 = 0, F1 = 1, f2 = 1, FN = Fn-2 + Fn-3 (n> = 3 ).
; 2006-12-15 Gao yuhan
The program does not consider dealing with negative numbers or overflow.
. 386
. Model flat, stdcall
Option Casemap: None
Includelib/masm32/lib/msvcrt. Lib
Printf proto C: DWORD,: vararg
Scanf proto C: DWORD,: vararg
. Data
Dvar dword 6
Szmsg1 byte 'enter an integer greater than 2: ', 0
Szmsg3 byte 'f % d = % d', 0ah, 0
Szmsg4 byte 'ebx = % d', 0ah, 0
Szinputfmt byte '% d', 0
. Code
Fibonacci proc C n: DWORD
Local dret: DWORD; stores the return values of subprograms.
Local DVAR: DWORD; stores N values (intermediate calculation ).
Cmp n, 2
Jle exitrecurse; n <= 2
Push n
Pop DVAR; DVAR = N
Dec DVAR; n-1
Invoke maid, DVAR; maid (n-1)
MoV dret, eax; Save the returned value of the last call.
Dec DVAR; equivalent to N-2
Invoke maid, DVAR; maid (n-2)
Add eax, dret; eax subroutine return value, eax = n-1 + N-2.
RET
Exitrecurse:
MoV eax, 1; Save the return value of the subroutine.
RET
Fibonacci endp
Start proc
Invoke printf, offset szmsg1; prompt.
Invoke scanf, offset szinputfmt, and offset DVAR; get the user input value.
Cmp dvar, 2
Jle exitrecurse; DVAR <= 2, exit.
MoV ECx, DVAR
Lop:
Push ECx; Save the ECX value.
Invoke Fibonacci, ECx
Invoke printf, offset szmsg3, ECx, eax
Pop ECx; restores the ECX value.
Loop Lop
Exitrecurse:
RET
Start endp
End start
Program running result:
Enter an integer greater than 2: 7
F7 = 13
F6 = 8
F5 = 5
F4 = 3
F3 = 2
F2 = 1
F1 = 1
Note:
There is a trap in the program: it uses recursive steps to calculate Fibonacci (n-1) and Fibonacci (n-2), but will also calculate Fibonacci (n-2) When computing Fibonacci (n-1 ), what is the extra computing cost?
The answer is: the cost is far more than one redundant computing: each recursive call triggers two other recursive calls, and either of these two calls triggers two recursive calls, the same is true for subsequent calls. In this way, the number of redundant computations increases rapidly. For example, in the recursive Calculation of Fibonacci (10), the value of Fibonacci (3) is calculated 21 times. However, during recursive computation of Fibonacci (30), the value of Fibonacci (3) was calculated 317,811 times. Of course, the results of these 317,811 computations are exactly the same, except for one of them, the rest is purely a waste. This extra overhead is really scary!
The above original sentence is taken from the p133 page in C and pointer (translated by the People's post and telecommunications press-jian th A. reek.