ProgrammingHardCodeforces-style · placement coding round

A solution must decide whether a number n up to 10^12 is prime within about one second in CPython. Which approach is correct and fast enough?

  1. A. Trial division by every integer below n, about 10^12 steps
  2. B. Trial division by integers up to the square root of n, about 10^6 steps
  3. C. A sieve over every integer up to n, which needs about 10^12 cells
  4. D. Checking every number below n/2 with a set of prime factors

Correct answer: B. Trial division by integers up to the square root of n, about 10^6 steps

Testing divisors only up to the square root is enough, which is about 10^6 steps and fits in a second. Options that visit every number below n or build a sieve of size n are far too slow or too large.

More Python Programming questions

Exams that ask this topic