Java 查找高达X复杂度的素数
该算法需要生成一个大小为X的数组,然后在索引中每个不是素数的数字都取零。。有人能告诉我复杂性是什么吗?为什么Java 查找高达X复杂度的素数,java,complexity-theory,primes,Java,Complexity Theory,Primes,该算法需要生成一个大小为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; } // "E
// 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;
}
}
//x是我们想要他下面所有素数的数字
int[]p=新的int[x+1];
//初始化数组。
对于(int i=2;i 对于(inti=2;i如果使用以下代码,时间复杂度为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;
}
}
}
int[]p=newint[x];
for(int i=0;i 对于(int i=4;我在Erastothenes的筛子上阅读了Wikipedia页面。你应该将j的定义更改为j=i*i。一旦更改,复杂性为O(x log x)。@user448810抱歉,这是不正确的。无论我们是从j=i*i
还是j=i*2
开始“擦除”,在随机访问聚合中,复杂性都是相同的O(1)
update,我假设Java数组是。