查找给定n的斐波那契指数的时间复杂度

时间:2019-10-29 06:12:06

标签: time-complexity fibonacci

这对我来说很难说,但是我很好奇如何计算迭代Fib(n)次的时间复杂度。

下面有一段代码,将迭代斐波纳契数,并从给定的输入中减去该数量。循环将运行n次,其中n为Fib(n) > input

代码的时间复杂度显然是Fib(n),但是如何用Big-O表示法表达出来呢?

我已经在math exchange上阅读了此内容,如果我理解正确,它表示时间复杂度为O(n log phi)或大约O(1.618n)。那么O(n)

那感觉很不对。

我还发现了(Fibonacci公式)[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;
  }

1 个答案:

答案 0 :(得分:2)

该数学交换链接所讨论的是log(Fib(n))而不是Fib(n)的渐近行为,因此不相关。

迭代Fib(n)次是指数运行时间。您可以通过查看第n个斐波纳契数的闭合形式公式来看到这一点:(称为Binet's formula

enter image description here

的增长类似于O(phi ^ n),其中phi为(1 + sqrt(5))/2,大约为1.618。

但是,您问题中的循环将重复O(Fibo(n))次。它将重复O(n)次。它具有通过迭代计算第n个斐波那契数的运行时间。