Question 991
What is printed?
int count = 0;
for (int i = 1; i <= 20; i++) {
boolean divisible = false;
for (int j = 2; j * j <= i; j++) {
if (i % j == 0) {
divisible = true;
}
}
if (!divisible && i > 1) {
count++;
}
}
System.out.println(count);Main Solution
This code counts the number of prime numbers from 2 to 20 (inclusive).
For each value of i from 1 to 20, the inner loop checks whether i has any divisor j in the range [2, √i]. If it does, divisible is set to true. After the inner loop, if !divisible && i > 1, then i is prime and count is incremented.
The primes from 2 to 20 are:
- 2 (inner loop doesn't execute since 2×2 = 4 > 2, so divisible stays false; 2 > 1 ✓)
- 3 (2×2 = 4 > 3, loop doesn't execute; divisible stays false; 3 > 1 ✓)
- 5 (2×2 = 4 ≤ 5, check 5 % 2 = 1 ≠ 0; divisible stays false ✓)
- 7 (2×2 = 4 ≤ 7, check 7 % 2 = 1 ≠ 0; divisible stays false ✓)
- 11 (2×2=4≤11: 11%2≠0; 3×3=9≤11: 11%3≠0; divisible stays false ✓)
- 13 (2×2=4≤13: 13%2≠0; 3×3=9≤13: 13%3≠0; divisible stays false ✓)
- 17 (2×2=4≤17: 17%2≠0; 3×3=9≤17: 17%3≠0; 4×4=16≤17: 17%4≠0; divisible stays false ✓)
- 19 (2×2=4≤19: 19%2≠0; 3×3=9≤19: 19%3≠0; 4×4=16≤19: 19%4≠0; divisible stays false ✓)
That gives us 8 primes: {2, 3, 5, 7, 11, 13, 17, 19}.
Therefore, count = 8 and the program prints 8.
Teacher Explanation
This is a classic primality-testing algorithm using trial division up to √i. The condition j * j <= i is equivalent to j <= Math.sqrt(i). The condition i > 1 excludes 1 (which is not prime). Students should recognize this as a prime-counting loop and enumerate the primes from 2 to 20: there are exactly 8 of them.
Education Coach Advice
When you see a nested loop with a condition like j * j <= i and a divisibility check, immediately recognize it as a primality test. Quickly list the primes up to the loop bound (here 20): 2, 3, 5, 7, 11, 13, 17, 19 — that's 8. Don't forget to check edge cases like i=1 (excluded by i > 1) and i=2 (inner loop never runs, so it's correctly counted as prime).
Traps
Common traps:
- Option A (7): Students may forget to count 2 as prime, since the inner loop condition
j * j <= imeans the inner loop never executes for i=2 (since 2×2=4 > 2). They might incorrectly think 2 is not handled. - Option C (9): Students might mistakenly include 1 as prime, forgetting the
i > 1guard. - Option D (10): Students might include both 1 and another non-prime, or miscount the primes up to 20.
Answer images

