MATH-P4

Primes in a window

Practice 4 of 7Number theory and counting12 tests

The problem

Return every prime p with lo <= p <= hi, as a list from smallest to largest.

primes_between(10, 30)    # [11, 13, 17, 19, 23, 29]
primes_between(91, 91)    # []: 91 = 7 * 13
primes_between(0, 2)      # [2]
primes_between(30, 10)    # []

Limits

  • hi is at most 10¹² (a million million), and the window hi - lo is at most about 2,000,000. lo may be below 2, or bigger than hi.
  • A sieve up to hi needs far too much memory, and testing each number by trial division is far too slow. The big tests have 4 seconds each.

Builds on MATH-4 The sieve of Eratosthenes.

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.

12 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2Empty windowNot run
3Below 2Not run
4One primeNot run
5One compositeNot run
6A square of a primeNot run
7Up to 100Not run
8Near a billionNot run
9Up to two millionNot run
10A window below 10¹²Not run
11A thin windowNot run
122 onlyNot run