ProgrammingHardTCS NQT · Infosys

A contest program must test whether n is prime for n up to 10^9 with a 1 second limit. Which method is fast enough for one query?

  1. A. trial division by every k from 2 to n - 1
  2. B. a sieve up to 10^9 rebuilt for each query
  3. C. trial division by every k with k * k <= n
  4. D. recursively test n - 1 down to 2

Correct answer: C. trial division by every k with k * k <= n

Checking divisors only up to the square root takes about 31623 steps for n = 10^9. The other options are either too slow or rebuild a huge sieve for every query.

More C Programming questions

Exams that ask this topic