【发布时间】:2019-10-29 06:12:06
【问题描述】:
这对我来说有点难以表达,但我很想知道如何计算迭代 Fib(n) 次的时间复杂度。
我有下面的一段代码,它将遍历斐波那契数并从给定的输入中减去该数量。循环将运行 n 次,其中 n 是Fib(n) > input。
代码的时间复杂度显然是Fib(n),但是如何用Big-O表示法来表达呢?
我在math exchange 上读过这篇文章,如果我理解正确的话,时间复杂度是O(n log phi) 或大约O(1.618n)。那么O(n)?
但感觉不对。
我还为(斐波那契公式)[http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html#section6] 找到了另一个资源,而这个似乎说它实际上是:
i ≈ log( N ) + (log(5) / 2) / log(Phi)
感觉上面说的更有意义。
public int findTheMaximumUsingALoop(int input) {
if (input == 1 || input == 2) {
return input;
}
int count = 2;
int next = 1;
int previous = 1;
input -= next + previous;
// loop until the next Fib number is more than we have left
while (input > 0) {
int tmp = previous;
previous = next;
next = next + tmp;
input -= next;
if (input >= 0) {
count++;
}
}
return count;
}
【问题讨论】: