Answer the question
In order to leave comments, you need to log in
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) + " ");
}
}
Answer the question
In order to leave comments, you need to log in
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; }
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 questionAsk a Question
731 491 924 answers to any question