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?
- A. Trial division by every integer below n, about 10^12 steps
- B. Trial division by integers up to the square root of n, about 10^6 steps
- C. A sieve over every integer up to n, which needs about 10^12 cells
- 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
- What is printed? python d = {'a': 1, 'b': 2} print(d.popitem(), d)
- What is printed? python print('{0}{1}{0}'.format('x', 'y'))
- What is printed? python print(list(filter(None, [0, '', [], [0], None])))
- What is printed? python print([i for i in range(10) if i % 3 == 0][::-2])
- What is printed? python print(set('mississippi') == set('misp'), len(set('mississippi')))
- What is printed? python print(0.1 3 == 0.3, abs(0.1 3 - 0.3) < 1e-9)