【发布时间】:2013-06-12 13:01:44
【问题描述】:
这个算法需要创建一个大小为 X 的数组,然后每个不是素数的数字在他的索引中置零。有人可以告诉我复杂度是多少吗?为什么?
// x is the number we want all the primes below him
int[] p = new int[x + 1];
// Initializes the array.
for (int i = 2; i < p.length; i++) {
p[i] = i;
}
// "Erases" the composite (non-prime) numbers.
for (int i = 2; i <= Math.sqrt(x); i++) {
for (int j = i * 2; j < p.length; j += i) {
p[j] = 0;
}
}
复杂度是O(x*sqrt(x))吗?
【问题讨论】:
-
阅读关于 Erastothenes 筛的维基百科页面。
-
你应该把j的定义改成j = i * i。一旦你这样做了,复杂度就是 O(x log log x)。
-
@user448810 抱歉,这是不正确的。无论我们从
j=i*i还是j=i*2开始“擦除”,复杂性都是相同的,在使用O(1)更新的随机访问聚合上,我假设Java 数组是。
标签: java complexity-theory primes