【问题标题】:Why doesn't the time complexity of Sieve of Eratosthenes algorithm have the argument sqrt(n)?为什么 Eratosthenes 算法的时间复杂度没有参数 sqrt(n)?
【发布时间】:2017-05-21 19:24:57
【问题描述】:

我试图了解埃拉托色尼筛算法的时间复杂度。网上到处都说时间复杂度是O(nloglog(n)),但我不明白为什么。

这是一些伪代码

factors =  new int[n+1];
for i from 2 to n
    factors[i] = 1; //true

for i from 2 to sqrt(n)
    if(factors[i] == 1) //isPrime
    {
        for all multiples of i upto n
            factors[multiple] = 0 //notPrime
    } 

return all indices of factors that have a value of 1

我想我们都同意这个函数的时间复杂度取决于嵌套的 for 循环。现在对其进行分析。当 i = 2 时,内循环运行 n/2 次。当 i = 3 时,内循环运行 n/3 次。下一次内部循环执行是下一个素数,所以 n/5 次。整个循环将运行

n/2 + n/3 + n/5 + n/7 + ... 次

这是

n(1/2 + 1/3 + 1/5 + 1/7 + ...)

直到 n 的素数的倒数之和是 O(log(log(n))) 的一个元素。 因此,总体复杂度为 O(nlog(log(n)))

但是,正如我们的伪代码中所写,外部 for 循环仅运行 root(n) 次。因此,我们只是将素数的倒数相加到 sqrt(n)。所以复杂度应该是O(nlog(log(sqrt(n)))) 而不是上面所说的。

我的分析有什么问题?

【问题讨论】:

    标签: algorithm primes sieve-of-eratosthenes


    【解决方案1】:

    O(nlog(log(sqrt(n)))) O(nlog(log(n))),因为 log(sqrt(n)) = log(n)/2 .

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-09
      • 2016-04-23
      • 1970-01-01
      • 2021-12-22
      • 2015-06-12
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多