Skip to content

Instantly share code, notes, and snippets.

@redsquirrel
Created October 15, 2012 12:03
Show Gist options
  • Select an option

  • Save redsquirrel/3892119 to your computer and use it in GitHub Desktop.

Select an option

Save redsquirrel/3892119 to your computer and use it in GitHub Desktop.
def fib_recursive(i, m = 0, n = 1, count = 0)
return m if count == i
fib_recursive(i, n, m+n, count+1)
end
def fib_iterative(i)
m, n = 0, 1
i.times do
m, n = n, m+n
end
m
end
@jfarmer
Copy link

jfarmer commented Oct 16, 2012

I FIGHT YOU

def fib_ewd(n, memo = {0 => 0, 1 => 1})
  return memo[n] if memo.has_key?(n)

  if n.even?
    memo[n] = (2 * fib_ewd(n / 2 - 1, memo) + fib_ewd(n / 2, memo)) * fib_ewd(n / 2, memo)
  else
    memo[n] = fib_ewd((n - 1) / 2, memo) ** 2 + fib_ewd((n + 1) / 2, memo) ** 2
  end
end

@jfarmer
Copy link

jfarmer commented Oct 16, 2012

require 'benchmark'

ITERATIONS = ARGV.fetch(0) { 100 }.to_i

Benchmark.bmbm do |x|
  x.report('fib_recursive') do
    ITERATIONS.times { fib_recursive(1000) }
  end

  x.report('fib_iterative') do
    ITERATIONS.times { fib_iterative(1000) }
  end

  x.report('fib_ewd') do
    ITERATIONS.times { fib_ewd(1000) }
  end
end

@jfarmer
Copy link

jfarmer commented Oct 16, 2012

jesse@thorin ~/code/scratch $ ruby fib_bench.rb 1000
Rehearsal -------------------------------------------------
fib_recursive   0.900000   0.000000   0.900000 (  0.901630)
fib_iterative   1.220000   0.000000   1.220000 (  1.218426)
fib_ewd         0.090000   0.000000   0.090000 (  0.091430)
---------------------------------------- total: 2.210000sec

                    user     system      total        real
fib_recursive   0.890000   0.000000   0.890000 (  0.891279)
fib_iterative   1.210000   0.000000   1.210000 (  1.215739)
fib_ewd         0.090000   0.000000   0.090000 (  0.089533)

@redsquirrel
Copy link
Author

You win the fight of most efficient/obfuscated code!

fib_ewd heel-kicks fib_recursive

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment