You could use "case" as well (see version 2). It's faster.
Using an ordinary if..else (without the elsif part) is faster
(see version 3). And version 4 is once again faster.
4 is faster than 3 is faster than 2 is faster than 1...
gegroet,
Erik V. - http://www.erikveen.dds.nl/
----------------------------------------------------------------
Version 1 100,0%
Version 2 90,3%
Version 3 72,7%
Version 4 70,2%
----------------------------------------------------------------
# VERSION 1
def fib(n)
if n == 0
return 0
elsif n == 1
return 1
else
return fib(n-1) + fib(n-2)
end
end
0.upto(30){|i| puts "The #{i} Fibonacci number is #{fib(i)}"}
# VERSION 2
def fib(n)
case n
when 0
1
when 1
1
else
fib(n-1) + fib(n-2)
end
end
0.upto(30){|i| puts "The #{i} Fibonacci number is #{fib(i)}"}
# VERSION 3
def fib(n)
if n<=1
1
else
fib(n-1) + fib(n-2)
end
end
0.upto(30){|i| puts "The #{i} Fibonacci number is #{fib(i)}"}
# VERSION 4
def fib(n)
n<=1 ? 1 : fib(n-1) + fib(n-2)
end
0.upto(30){|i| puts "The #{i} Fibonacci number is #{fib(i)}"}
----------------------------------------------------------------