ProgrammingHardTCS NQT · Accenture

The procedure below finds the largest prime less than 100 by testing each candidate from 99 down to 2 for divisibility by 2 up to its square root. What is printed?

The procedure below finds the largest prime less than 100 by testing each candidate from 99 down to 2 for divisibility by 2 up to its square root. What is printed?
for n = 99 down to 2
    prime = true
    for d = 2 to sqrt(n): if n mod d == 0 then prime = false
    if prime then print n and stop
end for
  1. A. 89
  2. B. 99
  3. C. 101
  4. D. 97

Correct answer: D. 97

97 is prime and nothing between 98 and 99 is, so the answer is 97. Limiting the search below 91 gives 89, dropping the primality test gives 99, and extending the range to 101 gives 101, which is not below 100.

More Pseudocode and Code Tracing questions

Exams that ask this topic