Project

General

Profile

Feature #1218 » fibonacci-tail-recursive.rb

This file computes the nth Fibonacci number using tail recursion. - Anonymous, 02/27/2009 12:13 AM

 
#!/usr/bin/env ruby -w

# compute nth fibonacci number in ruby using tail-recursion

def fibonacci_helper( a, b, count )

if count == 0
a
else
fibonacci_helper( b, a + b , count - 1 )
end

end

def fibonacci( n )

fibonacci_helper( 0, 1, n )

end

if __FILE__ == $0
if ( ARGV.length == 1 ) && ( ARGV.first.to_i.is_a? Integer )
puts fibonacci( ARGV.first.to_i )
else
raise ArgumentError, "Usage: fibonacci-tail-recusive.rb <integer>"
end

end
(3-3/3)