PythonMediumMath20 min
List all primes up to n
A prime has exactly two positive divisors. If n is less than two, print an empty line. Interviewers use this problem to assess mark multiples starting at each prime squared.
Input
One integer n.
Output
Print the result values separated by single spaces; print an empty line for an empty result.
Constraints
0 <= n <= 1000000.
Example
Input
20
Output
2 3 5 7 11 13 17 19
Example 2 input
49
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
The square of a prime must be excluded.
Public test cases (2)
Input
20
Expected output
2 3 5 7 11 13 17 19
Input
10
Expected output
2 3 5 7
Hints (2)
- Identify the state needed to avoid repeated work.
- Mark multiples starting at each prime squared.
Target complexity: time O(n log log n) · space O(n)
