RPL Programming Examples 2-3
FIB2 program listing
Program: Comments:
"!
#!G!
"!
Creates a local variable structure.
67!G!3!]!
:;<=!G!
<ED<!
8!3!
H!G!
D:BK:!
452!
KL:!
'!
!
=<T:!
DYB2!4KL2!
<=4!
1!
If n ≤ 1,
then F
n
= n;
otherwise …
Puts F
0
and F
1
on the stack.
From 2 to n does the following loop:
Copies the latest F (initially F
1
)
Gets the previous F (initially F
0
)
Calculates the next F (initially F
2
)
Repeats the loop.
Drops F
n-1
.
Ends the ELSE clause.
Ends the defining procedure.
»
`O FIB2 K
Stores the program in FIB2.
Checksum: # 23902d (press O%FIB2% !°#MEM# %BYTES%)
Bytes: 89
Example: Calculate F
6
and F
10
.
Calculate F
6
.
J
6 %FIB2%
Calculate F
10
.
10 %FIB2%
FIBT (Comparing Program-Execution Time)
FIB1 calculates intermediate values F
i
more than once, while FIB2 calculates each intermediate F
i
only once.
Consequently, FIB2 is faster. The difference in speed increases with the size of n because the time required for
FIB1 grows exponentially with n, while the time required for FIB2 grows only linearly with n.