Amazon Interview Question
Web DevelopersCountry: United States
This method still takes linear time. There are faster methods that take logarithmic time.
See geeksforgeeks .org/program-for-nth-fibonacci-number/ methods 4 and 5
Better still: stackoverflow .com/questions/1525521/nth-fibonacci-number-in-sublinear-time
f(n) = floor(phi^n / sqrt(5) + 1/2)
where phi represents the golden ratio.
Because it's still O(log n) but only 2 lines of code?
I don't see the benefit of implementing the matrix solution when you can just do it this way.
@jay: Perhaps looking at the downsides of using floating point computation will help you?
@jay, In Python you can use tuple assignment to make this a little more concise:
prev1, prev2 = (prev2+prev1, prev1)
Also, there is an O(log N) solution that uses only integer arithmetic. See "Python O(logN) version. "
better not to use recursive method , it will take a long time !
my solution resembles the above two but it has a plus point that,, for multiple inputs at the same time u just have to print those array elements;
int main()
{ long int a[1000000];
long int n;
a[0]=0;
a[1]=1;
for(i=2;i<;1000000;i++)
{ a[i]=a[i-1]+a[i-2];
}
cin>>n; //the number of which fib is required;
cout<<a[n];
return 0;
}
Python O(logN) version.
This uses some recursive properties of the Fibonacci numbers to compute an individual number in logN time. It's the most efficient solution that I know of that doesn't use floats. It's all integer multiplication and addition.
def fib(n):
if n == 0:
return 0
return fib2(n)[1]
def fib2(n):
# returns (fib(n-1), fib(n)
if n < 5:
return tuple([0,1,1,2,3,5][n-1:n+1])
x, y = fib2(n / 2)
a = x*x + y*y
b = (2*x+y)*y
if n % 2 == 1:
a, b = (b, a+b)
return (a, b)
for i in range(20):
print fib(i)
The most efficient way is iterative, only keeping the last two numbers in the sequence.
- jay March 23, 2013