可以斐波那契函数写在O(1)的时间来执行?写在、函数、时间

2023-09-11 01:52:30 作者:清风笑、烟雨摇

于是,我们看到了很多的问题斐波纳契。我个人恨他们。很多。多了许多。我认为这会是整齐的,如果我们也许可以把它任何人都不可能永远使用它作为一个面试问题了。让我们看看如何接近O(1),我们可以得到斐波纳契。

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.

下面是我的开球,从维基百科pretty的多crib'd,当然是有大量的空间。重要的是,该解决方案将引爆任何特别大的FIB,它包含一个比较幼稚的使用电源功能,在澳的地方吧(日志(N))在最坏的情况,如果你的库不是很好。我想我们可以摆脱电源的功能,或者至少是专注的。任何人都为帮助?是否有一个真正的O(1)的解决方案,不是使用一个查找表的有限*溶液中的其它

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.

推荐答案

由于随意性大的投入,只需读取n取O(log n)的,所以在这个意义上没有固定时间的算法是可行的。因此,使用封闭形式的解决方案,或precompute您所关心的值,来获得合理的性能。

Given arbitrary large inputs, simply reading in n takes O(log n), so in that sense no constant time algorithm is possible. So, use the closed form solution, or precompute the values you care about, to get reasonable performance.

编辑:在评论,有人指出,这实际上是糟糕的,因为斐波纳契是 0(PHI ^ N)打印在结果的斐波那契数是 O(日志(PHI ^ N)) O(N)

In comments it was pointed out that it is actually worse, because fibonacci is O(phi^n) printing the result of Fibonacci is O(log (phi^n)) which is O(n)!