V
V
Vladimir Stepanov2021-01-06 19:39:44
Java
Vladimir Stepanov, 2021-01-06 19:39:44

What is the order in which a variable is incremented in Java loops?

Good day and Happy New Year!
I broke my head with a problem of finding prime numbers, I found an algorithm, but I don’t want to pass it without understanding, so I ask you for help.

for(int i = 2; i <= 100; i++){
            boolean isPrime = true;
            for(int j = 2; j < i; j++){
                if(i % j == 0){
                    isPrime = false;
                    break;
                }
            }
            if(isPrime){

                System.out.printf(String.valueOf(i) + " ");
            }
        }


Here are two loops, with a check for the remainder of the division, but I can not figure out - in what order are the variables incremented for division without a remainder?

At the first iteration of the outer loop in the nested one, division 2 by 2 with remainder 0 is performed, the condition is met, break is triggered, the iteration in the outer loop is terminated (?) and the variable i is incremented, but j is not? My brain stubbornly resists coming to logic when trying to calculate several iterations further, please help me to clarify the moment.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Ezhgurov, 2021-01-06
@Simpelax

At each iteration of the outer loop, the inner loop starts anew - by creating the variable j, initializing it with the value 2, and so on.
Executing break only terminates the inner loop. The outer loop has been and continues to be executed until the value of i reaches 100.
With exactly the same result, the inner loop could be written without break:

for(int j = 2; isPrime && j < i; j++) { isPrime = i % j != 0; }

PS And the algorithm, to put it mildly, does not shine. The banal sieve of Eratosthenes is much more effective:
boolean[] arr = new boolean[100];
for(int i = 2; i < 100; ++i) {
  if (arr[i]) { continue; }
  for (int j = i * i; j < 100; j += i) { arr[j] = true; }
  System.out.print(i);
  System.out.print(' ');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question