Guest User

Untitled

a guest
Apr 25th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.54 KB | None | 0 0
  1. require 'matrix'
  2.  
  3. # fib1: Fast algorithm using the Golden Ratio
  4.  
  5. $sqrt5 = Math.sqrt 5
  6. $phi = (1 + $sqrt5) / 2
  7. def fib1 n
  8. (($phi**n - (1-$phi)**n) / $sqrt5).to_int
  9. end
  10.  
  11. # fib2: Naïve recursive algorithm
  12.  
  13. def fib2 n
  14. if n < 3
  15. 1
  16. else
  17. fib2(n-1) + fib2(n-2)
  18. end
  19. end
  20.  
  21. # fib3: Memoized recursive algorithm
  22.  
  23. $fibs = [0,1]
  24. def fib3 n
  25. $fibs.push($fibs[-1] + $fibs[-2]) until $fibs[n]
  26. $fibs[n]
  27. end
  28.  
  29. # fib4: Matrix multiplication shortcut
  30.  
  31. def fib4 n
  32. (Matrix[[1,1],[1,0]] ** n)[1,0]
  33. end
  34.  
  35. [1,2,3,4].each do |i|
  36. puts eval "fib#{i} 30"
  37. end
Add Comment
Please, Sign In to add comment