- Local time
- Today, 16:40
- Joined
- Sep 12, 2006
- Messages
- 16,044
last example - here is code to calculate the fibonacci series
1,1,2,3,5,8,13,21 etc - where each term is the sum of the previous 2
Here is normal code, and recursive code - the normal code has a couple of variables to manage the calculations, and a for next loop to control the iteration, and is pretty easy to follow.
the recursive code has very little, and is surprisingly tricky to understand.
unlike other ones we looked at, where we had subs, here we have a function which returns a value - and little else! No looping - it's all smoke and mirrors .....
1,1,2,3,5,8,13,21 etc - where each term is the sum of the previous 2
Here is normal code, and recursive code - the normal code has a couple of variables to manage the calculations, and a for next loop to control the iteration, and is pretty easy to follow.
the recursive code has very little, and is surprisingly tricky to understand.
unlike other ones we looked at, where we had subs, here we have a function which returns a value - and little else! No looping - it's all smoke and mirrors .....
Code:
[COLOR="Red"]Function fibonacci_recursive(term As Long)
If term = 1 Or term = 2 Then
fibonacci_recursive = 1
Else
fibonacci_recursive = fibonacci_recursive(term - 1) + fibonacci_recursive(term - 2)
End If
End Function[/COLOR]
[COLOR="Blue"]Function fibonacci_normal(term As Long) As Long
Dim x As Long
Dim thisval As Long
Dim lastval As Long
Dim newval As Long
thisval = 1 'hard code the first 2 terms in the series
lastval = 1
'so now we start the iteration at term 3
For x = 3 To term
newval = thisval + lastval
lastval = thisval
thisval = newval
Next
fibonacci_normal = newval
End Function[/COLOR]
[B][SIZE="3"]'{MAIN SUB to call both of the above methods}[/SIZE][/B]
Sub fib()
Dim term As Long
'this is the basic fbonacci series
'1,1,2,3,5,8,13,21,34,55,89,144
term = 12
'evaluate the result by a normal method, and then by a recursive method
MsgBox ("Fibonacci series (normal code): Term " & term & " is " & fibonacci_normal(term))
MsgBox ("Fibonacci series (recursive code): Term " & term & " is " & fibonacci_recursive(term))
End Sub
Last edited: