这个算法需要制作一个大小为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))?
答案 0 :(得分:0)
如果您使用以下代码,则时间复杂度为 O(x√x)。
int[] p = new int[x];
for (int i = 0; i < p.length; i++) {
p[i] = i+1;
}
for (int i = 4; i <= p.length; i++) {
for(int j = 2; j <= Math.sqrt(i) ; j += 1) {
if(i%j==0) {
p[i-1] = 0;
}
}
}