Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.53 KB | None | 0 0
  1. require 'benchmark'
  2.  
  3. class Fibonacci
  4. def self.calculate(n)
  5. return n if n <= 1
  6. calculate(n - 1) + calculate(n - 2)
  7. end
  8.  
  9. def self.calculate_with_memoization(n)
  10. @calculate ||= {}
  11. @calculate[n] ||= begin
  12. if n <= 1
  13. n
  14. else
  15. calculate_with_memoization(n - 1) + calculate_with_memoization(n - 2)
  16. end
  17. end
  18. end
  19. end
  20.  
  21. n = 30
  22.  
  23. Benchmark.bm(15) do |bm|
  24. bm.report('Without memoization') { Fibonacci.calculate(n) }
  25. bm.report('With memoization') { Fibonacci.calculate_with_memoization(n) }
  26. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement