Module: CompSci::Fibonacci
- Defined in:
- lib/compsci/fib.rb
Class Method Summary collapse
- .cache_iterative(n) ⇒ Object
- .cache_recursive(n, cache = {}) ⇒ Object
- .classic(n) ⇒ Object
- .dynamic(n) ⇒ Object
Class Method Details
.cache_iterative(n) ⇒ Object
13 14 15 16 17 |
# File 'lib/compsci/fib.rb', line 13 def self.cache_iterative(n) cache = [0, 1] 2.upto(n) { |i| cache[i] = cache[i-1] + cache[i-2] } cache[n] end |
.cache_recursive(n, cache = {}) ⇒ Object
8 9 10 11 |
# File 'lib/compsci/fib.rb', line 8 def self.cache_recursive(n, cache = {}) return n if n < 2 cache[n] ||= cache_recursive(n-1, cache) + cache_recursive(n-2, cache) end |
.classic(n) ⇒ Object
4 5 6 |
# File 'lib/compsci/fib.rb', line 4 def self.classic(n) n < 2 ? n : classic(n-1) + classic(n-2) end |
.dynamic(n) ⇒ Object
19 20 21 22 23 |
# File 'lib/compsci/fib.rb', line 19 def self.dynamic(n) a, b = 0, 1 (n-1).times { a, b = b, a+b } b end |