Skip to content

Instantly share code, notes, and snippets.

@Karlotcha
Created October 21, 2013 12:42
Show Gist options
  • Save Karlotcha/7083263 to your computer and use it in GitHub Desktop.
Save Karlotcha/7083263 to your computer and use it in GitHub Desktop.
Tail call recursion - Fibonacci
# tail call optimization
RubyVM::InstructionSequence.compile_option = {:tailcall_optimization => true,:trace_instruction => false}
# Fibonacci sequence
def fib(n,tail,tail2)
return 1 if n == 1
return 1 if n == 2
return tail + tail2 if n == 3
fib(n-1, tail2, tail+tail2)
end
# fib(100,1,1)
# Sum of the first elements of the Fibonacci sequence
def f(n,t1,t2,t3)
return 1 if n == 1
return 2 if n == 2
return t1+t2+t3 if n == 3
t=t1+t2
f(n-1, t2, t, t+t3)
end
# f(100,1,1,2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment