在Java中用i增加for循环整数j

时间:2013-09-30 20:51:31

标签: java loops for-loop sieve

我想把这个“伪代码”转换为可以在Java中运行的东西,我遇到了麻烦

for j = i², i²+i, i²+2i, ..., not exceeding n:

这是正确的吗?

for (int j = i*i; j < n; j++) {
    //other code here that does the operation:
    isPrime[j] = false;
    j = j+i;
}

2 个答案:

答案 0 :(得分:4)

你想要的是这个:

for (int j = i * i; j < n; j += i)
{
   isPrime[j] = false;
}

答案 1 :(得分:0)

我看到的第一个问题是你两次递增j。一旦进入声明,再次循环结束。你试过了吗?

for (int j = i*i; j < n; j+=i) {
    //other code here that does the operation:
    isPrime[j] = false;
}