SHARE
TWEET

Untitled

a guest Jul 23rd, 2019 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top