0

I want to turn this "pseudocode" into something that works in Java and I'm having trouble

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

Would this be correct?

for (int j = i*i; j < n; j++) {
    //other code here that does the operation:
    isPrime[j] = false;
    j = j+i;
}
Ry-
  • 218,210
  • 55
  • 464
  • 476
isaacn18
  • 1
  • 2
  • 1
    Do you know what the parts of a `for` loop do? You can just change the increment… – Ry- Sep 30 '13 at 20:52
  • Yes I understand the parts of a for loop. I'm having a conceptual problem understanding what to do. Can you maybe help explain what the fix would be in the incrementing part of the for loop? – isaacn18 Sep 30 '13 at 20:54
  • Could you be more specific on the algorithm? You actually increment j twice in your loop. Once in the loop declaration and then at the the end of your loop. – orgtigger Sep 30 '13 at 20:55
  • 1
    So you need j to be: i², i²+i, i²+2*i ? Seems that your real counter is k, where k is right here: i²+k*i – porfiriopartida Sep 30 '13 at 20:55
  • Got it, thanks. Still something in my overall code is not working. Guess I'll have to figure that out instead. Thanks everyone! – isaacn18 Sep 30 '13 at 20:57
  • This question appears to be off-topic because it belongs on[codereview.se]. – Cole Tobin Sep 30 '13 at 21:11

2 Answers2

4

What you want is this:

for (int j = i * i; j < n; j += i)
{
   isPrime[j] = false;
}
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
0

The first problem I see is that you are incrementing j twice. Once in the declaration and again at the end of the loop. Have you tried:

for (int j = i*i; j < n; j+=i) {
    //other code here that does the operation:
    isPrime[j] = false;
}
orgtigger
  • 3,914
  • 1
  • 20
  • 22