Guest User

Untitled

a guest
Apr 27th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. Q: Does the recursive version usually use less memory?
  2. A: No -- it usually uses more memory (for the stack).
  3.  
  4. Q: Then why use recursion??
  5. A: Sometimes it is much simpler to write the recursive version (but
  6.  
  7. factorial(n) = if n = 0 then 1 else n * factorial(n - 1)
  8.  
  9. factorial(n) = f_iter(n, 1)
  10.  
  11. f_iter(n, a) = if n = 0 then a else f_iter(n - 1, n * a)
  12.  
  13. a = 1;
  14. while (n != 0) {
  15. a = n * a;
  16. n = n - 1;
  17. }
  18. return a;
  19.  
  20. #recursive version
  21. def fib(n):
  22. if n==0 or n==1:
  23. return n
  24. else:
  25. return fib(n-1)+fib(n-2)
  26.  
  27. #iterative version
  28. def fib2(n):
  29. if n==0 or n==1:
  30. return n
  31. prev1,prev2=0,1 # start from the base case
  32. for i in xrange(n):
  33. cur=prev1+prev2 #build the solution for the next case using the previous solutions
  34. prev1,prev2=cur,prev1
  35. return cur
  36.  
  37. f (n) = n if n<3
  38. f (n) = f (n - 1) + 2f (n - 2) + 3f (n - 3) if n>= 3
Add Comment
Please, Sign In to add comment