python - 下面函数的运行时间

标签 python algorithm data-structures big-o time-complexity

外循环运行了n次,但我找不到内循环的运行时间和总运行时间,请问你能帮忙解决这个问题吗?

def function(n)
    count=0
    if n<=0:
        return
    for i in range(1,n):
        j=1
        While j<n:
            j=j+i
            count = count+1
    print(count)

最佳答案

对于 i 的每个值,内部循环运行 O(n/i) 次。

如果我们对 i 的所有值求和,我们得到:

n/1 + n/2 + n/3 + ... + n/n = n* (1 + 1/2 + ... + 1/n)

总和 1 + 1/2 + ... + 1/nharmonic number ,它在 O(logn) 中,所以你的代码是 O(nlogn)

关于python - 下面函数的运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33352268/

相关文章:

ruby-on-rails - Ruby 中的哈希 "has_key"复杂性

python - 使用列表理解从嵌套的 Python 数据结构中获取值列表?

python - 我是否正确使用 scipy.linalg.solve_discrete_lyapunov

python - 如何管理跨多个数据集的查找

python - Python 3 中从外部父类的嵌套类继承的嵌套类

algorithm - 计算走 1、2 或 3 步后爬 n 步的方法

algorithm - 用于搜索/自动完成的 Elasticsearch 或 Trie?

python - 从 Excel 到分割的 Python 结构

algorithm - B+树插入顺序

python - 将 RGB 转换为 HLS 并返回