Absolutely slow (because it recurses until n reaches a depth of 0 or 1).
def fib(n)
return n if n == 0 || n == 1
return fib(n - 1) + fib(n - 2)
end
It's recursion, but what you're doing isn't much different from a for statement. It's just a recursive function, so if a super big n is passed, it may overflow the stack?
def fib(n, a, b)
return a if n == 0
return fib(n - 1, b, a + b)
end
Since it is not recursion, stack overflow will not occur ... You can write beautifully by using split assignment. This is a split assignment.
def fib(n)
a, b = 0, 1
n.times.each { a, b = b, a + b }
a
end
TODO Please write someone.
Recommended Posts