Skip to content

Instantly share code, notes, and snippets.

@PickledChair
Created November 23, 2019 12:00
Show Gist options
  • Save PickledChair/3ac4c80abc089ebc0eb0e6cfe873e182 to your computer and use it in GitHub Desktop.
Save PickledChair/3ac4c80abc089ebc0eb0e6cfe873e182 to your computer and use it in GitHub Desktop.
fibonacci recursive function for Ruby
=begin
# mruby doesn't have the even? method.
class Integer
def even?
self % 2 == 0
end
end
=end
def trcall(value)
while value.instance_of?(Proc)
value = value.call
end
value
end
def fib(n)
trcall(fib_iter(1, 0, 0, 1, n))
end
def fib_iter(a, b, p, q, count)
return b if count.zero?
if count.even?
np = p**2 + q**2
nq = 2*p*q + q**2
nc = count.div(2)
proc {fib_iter(a, b, np, nq, nc)}
else
na = b*q + a*q + a*p
nb = b*p + a*q
nc = count - 1
proc {fib_iter(na, nb, p, q, nc)}
end
end
# 100.upto(110){|i| puts fib(i)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment