Created
October 21, 2013 12:42
-
-
Save Karlotcha/7083263 to your computer and use it in GitHub Desktop.
Tail call recursion - Fibonacci
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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