HARD-P5

Prime or not

Practice 5 of 5Hard problems13 tests

The problem

Return whether a whole number n is prime, for any n from 0 up to just below 3 × 10²⁴. The answer must always be right: no chance of error is allowed.

is_prime(97)     # True
is_prime(561)    # False: 3 · 11 · 17
is_prime(2047)   # False: 23 · 89

Limits

  • Trial division up to √n is far too slow for large n.
  • Some tests ask about thousands of numbers at once.
  • The numbers include composites built to fool weaker tests: Carmichael numbers, and numbers that pass the strong test for many bases.

Builds on HARD-5 Randomised algorithms.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

13 tests, not run yet
Test results
#TestResultReads · time
1Small numbersNot run
2A Carmichael numberNot run
3More Carmichael numbersNot run
4Fools base 2Not run
5Fools bases 2, 3, 5 and 7Not run
6Fools the first nine primesNot run
7Fools the first twelve primesNot run
8A big primeNot run
9A square of a big primeNot run
10Two prime factors near 10¹²Not run
11Near 10²⁴Not run
12Primes near 10¹⁸Not run
13Primes below 200,000Not run