Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Q: Does the recursive version usually use less memory?
- A: No -- it usually uses more memory (for the stack).
- Q: Then why use recursion??
- A: Sometimes it is much simpler to write the recursive version (but
- factorial(n) = if n = 0 then 1 else n * factorial(n - 1)
- factorial(n) = f_iter(n, 1)
- f_iter(n, a) = if n = 0 then a else f_iter(n - 1, n * a)
- a = 1;
- while (n != 0) {
- a = n * a;
- n = n - 1;
- }
- return a;
- #recursive version
- def fib(n):
- if n==0 or n==1:
- return n
- else:
- return fib(n-1)+fib(n-2)
- #iterative version
- def fib2(n):
- if n==0 or n==1:
- return n
- prev1,prev2=0,1 # start from the base case
- for i in xrange(n):
- cur=prev1+prev2 #build the solution for the next case using the previous solutions
- prev1,prev2=cur,prev1
- return cur
- f (n) = n if n<3
- f (n) = f (n - 1) + 2f (n - 2) + 3f (n - 3) if n>= 3
Add Comment
Please, Sign In to add comment