r/csinterviewproblems • u/parlezmoose • Dec 17 '15
[Recursion] Write a function to print the n'th Fibonacci number
The Fibonacci sequence is defined by the function:
f(n) = f(n-1) + f(n-2)
f(0) = 0
f(1) = 10, 1, 1, 2, 3, 5, 8...
Write a function to print the n'th number in this sequence.
Sample input: 4
Sample output: 3
Follow up: Can you do it without recursion?
3
Upvotes
2
u/[deleted] Dec 18 '15
There is a way to cheat using binet's formula if you only need the nth number. You can simply use:
If you need all of the numbers up till the nth number then you can use matrix operations to speed it up. Here is a program that shows the matrix operations in C++ and an explanation of the algorithm
1
u/parlezmoose Dec 17 '15
1
u/quadmra Dec 18 '15
Just had to do this one today. Yikes. Really caught me off guard with the follow up without recursion. Hated that :/
1
u/ewjqbehjwqbehjqw Dec 19 '15
Seriously, no tail-recursion has been posted yet? Ya'll blowing up your stacks in every single recursive solution posted so far.
This solution sucks too, because you're going to get integer overflow. Use a bigint lib.
1
u/[deleted] Dec 19 '15
No Recursion : Java
0
u/[deleted] Dec 17 '15
[deleted] — view deleted comment