【问题标题】:Time complexity of finding the Fibonacci index for a given n查找给定 n 的斐波那契指数的时间复杂度
【发布时间】: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;
  }

【问题讨论】:

    标签: time-complexity fibonacci


    【解决方案1】:

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

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

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2019-01-05
    相关资源
    最近更新 更多