algorithm - 寻找素数的简单算法的复杂性

标签 algorithm time-complexity primes asymptotic-complexity

我想知道这个寻找素数的简单算法的渐近复杂度是否为 O(n):

PrimeNumber(n)
Int i;
If (n%2=0) then { return "not prime"; }
Else {
  For(i=3;i<(√n)+1;i=i+2;){
    If (n%i=0) then {return "not prime";}
  }     
}
return "prime";

最佳答案

时间复杂度为 O(sqrt(n)),因为循环自身迭代了 (sqrt(n)+1-3)/2 次,这在O(sqrt(n))

请注意,由于 O(sqrt(n))O(n)子集,所以这样说也是正确的是 O(n) - 但这个界限并不严格。

关于algorithm - 寻找素数的简单算法的复杂性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44072198/

相关文章:

c++ - 在递归函数中使用字符串的 size() 函数会导致较大的延迟/复杂性吗?

c++ - 作业帮助 : Prime Number Identifier C++

algorithm - 汉明距离可以用于非二进制结构吗

c - 减去数组

python - 二次时间复杂度 : why is the following code calculated this way?

c++ - 动态内存分配会增加运行时间吗?

c++ - 你能告诉我为什么这会产生超过 spoj(质数生成器)的时间限制吗

C - 获取整数数组的特定内容并将它们放入另一个数组中

java - 用于快速检索、更新和保持排序的最佳数据结构

algorithm - 如何计算有向图中所有可达节点?