ProgrammingModerateAccenture · Cognizant pattern

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer count = 0
for (i = 2 to 30)
    Boolean prime = true
    for (d = 2 while d * d <= i)
        if (i mod d == 0) prime = false
    end for
    if (prime) count = count + 1
end for
Print count
  1. A. 11
  2. B. 13
  3. C. 10
  4. D. 0

Correct answer: C. 10

Trial division up to √i finds the primes from 2 to 30: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ten of them. Using d * d < i misses the prime squares 4, 9, 25 (13), starting i at 1 would count 1 (11), and starting d at 1 makes every number composite (0).

More Pseudocode and Code Tracing questions

Exams that ask this topic