【问题标题】:Total Time Complexity of Nested Big-O's嵌套 Big-O 的总时间复杂度
【发布时间】:2021-11-14 14:19:43
【问题描述】:

我编写了一个程序来计算一个数字的阶乘,并将结果的数字存储在 Python 列表中。

  1. 为了找到阶乘,我运行了一个需要 O(N) 的循环并将结果存储在“ans”中
  2. 为了找到“ans”的位数,我运行了另一个循环,该循环采用 log10(ans)。
  3. 最后,我只是原地反转列表

我很难知道总时间复杂度 (TC) 是多少。我相信:

TC = O(d) = O(log10(ans)),因为对于 N->inf d > N,其中 d(ans 中的位数)= log10(ans),并且 ans ∈ O(N) .

我错了吗?有没有其他方式来表达总TC,也许像嵌套的Big-O:

O(log10(O(N))) ???

注意:log10 表示以 10 为底的对数

下面是我的代码:

def factorial(N):
        ans = N
        ans_digits = []

        # 1. O(N)
        while N > 1:
            N -= 1
            ans *= N

        # 2. O(log10(ans))
        while ans > 0:
            digit = ans % 10
            ans //= 10
            ans_digits.append(digit)

        # 3. O(log10(ans))
        for i in range(len(ans_digits)//2):
            temp = ans_digits[i]
            ans_digits[i] = ans_digits[-(i+1)]
            ans_digits[-(i+1)] = temp

        # Shorter way of doing 2 and 3: O(log10(ans))
        #ans_digits = str(ans).split()

        return ans_digits

【问题讨论】:

  • 是的,TC = O(d),因为 d > N 表示大 N。要用 N 表示 O(d),需要使用 Stirling's approximation
  • 或者您可以通过注意大多数乘法将 O(logN) 数字添加到答案来近似 TC。无论哪种方式,以 N 表示的时间复杂度都是 O(NlogN)。
  • @user3386109:如果我错了,请纠正我。所以 TC = O(d) = O(logn!) = O(nlogn - c.n + O(logn)) = O(nlogn) ?
  • 是的,没错。

标签: algorithm data-structures time-complexity computer-science


【解决方案1】:

感谢@user3386109,Stirling's approximation 对阶乘,时间复杂度可以用 N 表示为:

TC = O(d) = O(logN!) = O(NlogN - c.N + O(logN)) = O(NlogN)

其中log 的底数为 10,N 为整数。

【讨论】:

  • 对于 Big-O,我们并不真正关心 log 是 base10 还是 base2 或 base 什么的,因为它们只有一个常数不同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
  • 2019-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多