So I've been working on this according to the challenge @PeterTaylor gave me. I'm not very good at math, so I've been doing a lot of reading and found this link on the Binet form. Fibonacci algorithms
Unfortunately, when I use this in Ruby, it typically returns Infinity above 1000 or so for n. It works well for smaller equations, but not so much for very large numbers.
Here is the code I wrote for it.
a = (1 + Math.sqrt(5))/2 b = (1 - Math.sqrt(5))/2 #here, n == 5 f = ((a**5) - (b**5))/(a-b)
When you round f.to_i, it returns 5.
Back to the drawing board.
Original post below
Practicing recursion some more, and I'm wondering if this is the proper solution for this exercise I'm doing.
First, my code in Ruby:
def fibonacci(num, fact=[1,1]) x = fact[fact.length-1] y = fact[fact.length-2] if fact[num-1] return fact[num-1] else fibonacci(num, fact.push(x+y)) end end p fibonacci(5) p fibonacci(12) == 144 p fibonacci(20) == 6765 p fibonacci(8200)
The exercise is this: Write a recursive method that computes the nth Fibonacci number, where nth is an argument to the method.
So, the 12th fibonacci number (which would be fact due to indexing) is 144.
I know that I am returning the correct number, and that the recursion stops once fact[num-1] returns true. I can't help but feel that this is not the best way to do this, or even the proper way to do this.
Thoughts? Any advice?