So, we see a lot of fibonacci questions. I, personally, hate them. A lot. More than a lot. I thought it'd be neat if maybe we could make it impossible for anyone to ever use it as an interview question again. Let's see how close to O(1) we can get fibonacci.
Here's my kick off, pretty much crib'd from Wikipedia, with of course plenty of headroom. Importantly, this solution will detonate for any particularly large fib, and it contains a relatively naive use of the power function, which places it at O(log(n)) at worst, if your libraries aren't good. I suspect we can get rid of the power function, or at least specialize it. Anyone up for helping? Is there a true O(1) solution, other than the finite* solution of using a look-up table?
http://ideone.com/FDt3P
#include <iostream> #include <math.h> using namespace std; // would never normally do this. int main() { int target = 10; cin >> target; // should be close enough for anything that won't make us explode anyway. float mangle = 2.23607610; float manglemore = mangle; ++manglemore; manglemore = manglemore / 2; manglemore = pow(manglemore, target); manglemore = manglemore/mangle; manglemore += .5; cout << floor(manglemore); }
*I know, I know, it's enough for any of the zero practical uses fibonacci has.
The Fibonacci sequence begins with the following 14 integers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 ... Each number, starting with the third, adheres to the prescribed formula. For example, the seventh number, 8, is preceded by 3 and 5, which add up to 8.
The time complexity of the Fibonacci series is T(N) i.e., linear. We have to find the sum of two terms, and it is repeated n times depending on the value of n. The space complexity of the Fibonacci series using dynamic programming is O(1).
The Fibonacci sequence is a series of numbers where a number is the addition of the last two numbers, starting with 0, and 1. The Fibonacci Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55… This guide provides you with a framework for how to transition your team to agile.
The four internal nodes of this tree for fib(5) take two lines each, while the five leaves take one line, so the total number of lines executed in all the recursive calls is 13.
Here is a near O(1)
solution for a Fibonacci sequence term. Admittedly, O(log n)
depending on the system Math.pow() implementation, but it is Fibonacci w/o a visible loop, if your interviewer is looking for that. The ceil()
was due to rounding precision on larger values returning .9 repeating.
Example in JS:
function fib (n) { var A=(1+Math.sqrt(5))/2, B=(1-Math.sqrt(5))/2, fib = (Math.pow(A,n) - Math.pow(B,n)) / Math.sqrt(5); return Math.ceil(fib); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With