The primes up to n
- O(n log n) · Hard
- Full plan
- Python
- JavaScript
- lists
- loops
- operations
Problem
A prime number can only be divided by 1 and by itself. The 1 does not count as prime: the first one is 2.
Write a function that takes a number n and returns the list of the primes from 2 up to n, from smallest to largest. If n is prime, it goes in too. With n smaller than 2 there are none, so you return an empty list.
An old trick to do it without dividing so much: write down every number from 2 to n and cross out the multiples of each prime you find. What is left uncrossed is the answer.
Examples
Nothing before 2
1 → []
The first prime
2 → [2]
Up to 10
10 → [2, 3, 5, 7]
n is prime
13 → [2, 3, 5, 7, 11, 13]
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def primes_up_to(n):
passJavaScript
function primesUpTo(n) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.