Quick revision
The short answer
Printing all primes up to N is a math problem solved by the Sieve of Eratosthenes. Instead of testing each number, every prime crosses out its multiples in a boolean array, starting from its square, and the numbers left unmarked are the primes. It runs in O(N log log N) time with O(N) space.
The solution
What it costs
| Approach | Time | Extra space | Work for N = 30 |
|---|---|---|---|
| Test each number by trial division | O(N sqrt N) | O(1) | 45 divisions |
| Sieve, crossing from 2p | O(N log log N), more writes | O(N) | more writes, same answer |
| Sieve, crossing from p squared | O(N log log N) | O(N) | 24 writes |
What to remember
We listed every prime up to N with the Sieve of Eratosthenes: walk i from 2, and whenever i is still unmarked it is prime, so cross out its multiples from i times i, stopping once i times i passes N. The numbers left unmarked are the primes. It takes O(N log log N) time and O(N) space, against O(N sqrt N) for testing each number. The clue to remember is the word all with a divisibility question: let each small number mark its multiples instead of testing every number on its own.
1What it means to list every prime up to N
Think of a kitchen sieve. You pour in flour with a few lumps, shake it, and the fine flour falls through while the lumps stay behind. We are going to do the same with numbers. We pour in every number from 2 to N, shake out the ones that are not prime, and whatever stays behind is the answer. The method is even called a sieve, the Sieve of Eratosthenes, after the Greek scholar who described it.
First, the words. A divisor of a number is a whole number that divides it with nothing left over; 3 is a divisor of 12, because 12 is 3 times 4. A prime is a whole number greater than 1 whose only divisors are 1 and itself. So 2, 3, 5 and 7 are prime. 9 is not, because 3 divides it. A number above 1 that is not prime is called composite. And 1 is not prime, by definition, so our list always starts at 2.
Let us do the example by hand for N = 30. Go through the numbers and ask of each one whether something smaller than it, other than 1, divides it. 21 is 3 times 7, so it is out. 25 is 5 times 5, so it is out. 29 has no divisor except 1 and 29, so it stays. When we finish, ten numbers remain: 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29.
The numbers 1 to 30 in rows of ten, with the primes highlighted.
- 21
- 3 x 7, not prime
- 25
- 5 x 5, not prime
- count
- 10
1Of the numbers from 1 to 30, exactly ten are prime: 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29. These are what we must return.
What to assume
- Is N itself included?
- We assume yes.
- How large can N be?
- We assume up to a few tens of millions, so an array of N true or false values fits in memory.
- What should we return?
- The primes in increasing order, as a list.
- And for N below 2?
- An empty list.
This problem is gentler than it looks. It needs no formula and no clever mathematics, only the definition of a prime and the patience to cross numbers out in the right order. A careful candidate still asks a few questions. Is N itself included? We assume yes. How large can N be? We assume up to a few tens of millions, so an array of N true or false values fits in memory. What should we return? The primes in increasing order, as a list. And for N below 2? An empty list.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to spot the pattern in a question about every number
On a first reading, most beginners think of one number at a time. We know how to check whether a single number is prime, by trying to divide it, so the natural plan is to do that check for 2, then for 3, then for 4, all the way to N. That plan is a fine start, and we will write it next. But the words of the question hint at something better.
The first clue is the word all. When a question asks about one number, such as whether 97 is prime, we test that number. When it asks about every number up to a limit, the answers for different numbers are related, and work done for one can help the others.
The second clue is that the property is about divisibility. Divisibility runs in both directions: asking which numbers divide x is the same fact as asking which numbers are multiples of d. Finding multiples is easy, because the multiples of 3 are just 3, 6, 9 and so on, one addition apart.
The third clue is up to N. The numbers 2 to N are consecutive whole numbers, so they can serve directly as positions in an array. We can keep one true or false mark per number, with no searching and no map.
These clues place the problem in the math and bits family, and point to a technique called a sieve. A sieve stops testing numbers one by one and instead lets each small number mark its multiples in an array. The rule to carry to new problems is this: when a question asks for a divisibility fact about every number up to N, such as all primes, the smallest prime factor of each number, or how many divisors each has, mark multiples in an array instead of testing each number.
Two neighbours look similar but do not fit. Dynamic programming also reuses earlier results, but there is no formula linking one answer to the previous ones here; a number is prime simply because nothing smaller marked it. And a hash set of found primes would only add work, since the numbers are already perfect array indexes.
3The honest first attempt, testing each number on its own
The first method anyone would write, the brute force, tests every number from 2 to N separately. To test x, we try dividing it by 2, then 3, then 4, and so on. If any of them divides x with nothing left over, x is composite. If none does, x is prime.
How far must we try? A beginner might go all the way to x - 1, but we can stop much sooner, at the square root of x. Here is why. Divisors come in pairs: 36 is 2 times 18, 3 times 12, 4 times 9 and 6 times 6. In every pair, one number is at most 6, the square root of 36, and the other is at least 6. So if x has any divisor besides 1 and itself, it has one no bigger than its square root, and trying up to the square root is enough. For 29, the square root is a little above 5, so we try 2, 3, 4 and 5, find no divisor, and say 29 is prime.
Now let us count. For N = 30, this code makes 45 divisions in all. Testing one number x costs up to the square root of x divisions, so the whole list costs about N times the square root of N, written O(N sqrt N). For N of ten million, that bound is about thirty billion; numbers with a small divisor stop early, but every prime must try every divisor up to its square root. The extra space is O(1), apart from the output.
So where is the waste? Look at the number 91. We try 2, 3, 4, 5, 6 and finally 7, which divides it. But dividing by 4 could never succeed, because if 4 divided 91 then 2 would have divided it first, and 2 already failed. The same goes for 6. Worse, each number is tested from scratch: the knowledge that 4, 6 and 8 are not prime is learned again and again, and never shared between tests.
4Turning the question around, from testing to crossing out
That waste suggests turning the problem around. Instead of asking each number who divides it, we let each prime announce that all of its multiples are composite. We keep a boolean array called composite, with one place for each number from 0 to N. composite[x] = false means x has not been ruled out yet, so every place starts as false, unmarked.
We walk a number i upward from 2. When we reach i, we look at composite[i]. If it is still false, i is prime, and we mark every multiple of i, that is i times 2, i times 3 and so on up to N, as composite. Then we move to the next i. When the walk ends, the numbers still unmarked are exactly the primes.
Now the question a beginner always asks. How can we be sure that an unmarked i is prime? We never tried dividing it. Think of it this way. If i were composite, it would have a divisor smaller than itself, and that divisor, or one of its own divisors, would be a prime p smaller than i. We reached p earlier in the walk, found it unmarked, and crossed out all multiples of p, and i is one of them. So a composite i is always marked before we reach it, and an unmarked i must be prime.
Two refinements make the sieve fast. First, for a prime p we can start crossing out at p times p rather than 2 times p. Every smaller multiple, k times p with k less than p, has a prime factor smaller than p, so it was crossed out in an earlier pass. For p = 5, the numbers 10, 15 and 20 were already crossed by 2 and 3, so we start at 25.
Second, the outer walk can stop once i times i is greater than N. Any composite up to N has a divisor no bigger than the square root of N, the same pair argument as before, so by then every composite has been marked. For N = 30 we stop at i = 6, since 36 is past 30. In Java we write the test as (long) i * i <= n, so that i times i cannot overflow an int when N is close to two billion.
The mistake beginners most often make is to start the inner loop at i instead of i times i or 2 times i. Starting at i crosses out the prime itself, so 2, 3 and 5 would vanish from the answer.
5Watching the sieve shake out the composites up to 30
The picture runs the sieve on N = 30. The numbers 1 to 30 sit in three rows of ten. A number crossed out in an earlier pass is dimmed, a number crossed in the current pass is marked now, a number crossed again although it was already out is marked compared, and primes are marked found.
Watch how few passes there are, and how each pass crosses fewer new numbers than the one before.
The numbers 1 to 30 in rows of ten. Crossed-out numbers are dimmed, numbers crossed in this pass are marked now, numbers crossed again are marked compared, and primes are marked found.
- i
- not started
- crossed so far
- 0
1Every number starts unmarked, meaning it might be prime. 1 is dimmed because 1 is not prime by definition, so we begin at 2.
- i
- 2
- i x i
- 4, not past 30
- primes found
- 2
2i = 2 is still unmarked, so no smaller number divides it, and 2 is prime. Its pass will start at 2 x 2 = 4.
- i
- 2
- this pass
- 14 crossed
- writes so far
- 14
3We cross out 4, 6, 8 and every second number up to 30. That is 14 numbers, every even number except 2.
- i
- 3
- start at
- 9
- new this pass
- 9, 15, 21, 27
- writes so far
- 22
4i = 3 is unmarked, so 3 is prime. We start at 3 x 3 = 9 and cross 9, 12, 15, ... 30. Only 9, 15, 21 and 27 are new.
- i
- 4
- composite[4]
- true, skip
- writes so far
- 22
5i = 4 is already crossed out, by 2, so it is not prime and we skip it. Its multiples were all crossed by 2 already.
- i
- 5
- start at
- 25
- new this pass
- 25
- writes so far
- 24
6i = 5 is unmarked, so 5 is prime. We start at 25 and cross 25 and 30. 10, 15 and 20 were crossed earlier by 2 and 3.
- i
- 6
- i x i
- 36 > 30, stop
- writes in all
- 24
7i = 6 would need 6 x 6 = 36, which is past 30, so the outer loop stops. Every composite up to 30 is already crossed.
- primes
- 2 3 5 7 11 13 17 19 23 29
- count
- 10
8The final scan collects every number from 2 to 30 that is still unmarked: 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29.
Let us read the important frames back. In the third frame, the pass for 2 crosses out fourteen numbers, every even number except 2 itself. In the fourth, the pass for 3 starts at 9 and crosses eight numbers, but only 9, 15, 21 and 27 are new; 12, 18, 24 and 30 were already out because they are even.
In the fifth frame, i = 4 is already crossed, so the loop skips it without doing any work. In the sixth, the pass for 5 starts at 25 and finds only one new number, 25 itself; 30 was crossed before. Then i = 6 fails the test 6 x 6 <= 30, and the outer loop ends. Only three primes, 2, 3 and 5, ever crossed anything out, with 24 writes in all, and the last frame collects the ten primes we found by hand.
6The complete Java program
Here is the full class. The method returns a list, so the caller decides how to print it. main prints the primes up to 30, the smallest case with a prime, a case with none, and how many primes there are below one million, a well-known value we can check against.
Let us read primesUpTo in the order it runs. If n is below 2, there are no primes, and we return the empty list before allocating anything. Otherwise we create composite with n + 1 places, so that composite[n] exists; Java fills a new boolean array with false, which is exactly the unmarked state we want.
The outer loop walks i from 2 while (long) i * i <= n. Inside it, if composite[i] is true, i was crossed out by a smaller prime, so i is not prime and continue moves straight to the next i. Otherwise i is prime, and the inner loop starts j at i * i and adds i each time, setting composite[j] = true. Starting at i * i cannot overflow, because the outer test has already made sure that i * i is at most n.
When the crossing out is over, the last loop walks from 2 to n and adds every number whose place is still false. That is also where primes above the square root of n, such as 7, 11 and 29 for n = 30, are collected; they never crossed anything out, but they were never crossed out either. main prints the ten primes up to 30, then [2], then [], and then 78498.
7How much it costs, and the cases at the edges
Let us count on the example first. The three passes made 14, 8 and 2 writes, 24 in all, and the final scan looked at 29 numbers. Testing each number on its own made 45 divisions for the same answer. The gap grows quickly as N grows.
In general, the pass for a prime p crosses out about N divided by p numbers, so the total is N/2 + N/3 + N/5 + N/7 and so on, over the primes up to the square root of N. Mathematicians have shown that this sum grows like N times log log N, where log log N is a function that grows so slowly that it stays below 4 even for N in the billions. So the sieve runs in O(N log log N) time, which behaves almost like a single pass over the numbers. The final scan adds O(N).
The space is O(N), for the boolean array. Java stores each boolean in one byte, so ten million numbers need about ten megabytes.
| Approach | Time | Extra space | Work for N = 30 |
|---|---|---|---|
| Test each number by trial division | O(N sqrt N) | O(1) | 45 divisions |
| Sieve, crossing from 2p | O(N log log N), more writes | O(N) | more writes, same answer |
| Sieve, crossing from p squared | O(N log log N) | O(N) | 24 writes |
The edge cases are all handled. For N below 2 we return an empty list before allocating anything. For N = 2 the outer loop never runs, since 2 x 2 is more than 2, and the scan finds 2 unmarked, so we return [2]. For very large N, the long in the outer test prevents overflow. If N is so large that N booleans do not fit in memory, we switch to the segmented sieve described in the follow-up questions.
8Follow-up questions
What if N is a billion and the array does not fit in memory?
We use a segmented sieve. First we sieve normally up to the square root of N, about 31,623 for a billion, which gives every prime we will ever need for crossing out. Then we walk the range from 2 to N in blocks, say a million numbers at a time. For each block we make a small boolean array and, for every base prime p, cross out its multiples that fall inside the block, starting from the first multiple at or after the block's start, and never below p times p. Memory stays at one block plus the base primes, and the total time is still O(N log log N).
Can the sieve be made truly linear?
Yes. The linear sieve keeps a list of the primes found so far and, for each i, marks i times p only for primes p up to the smallest prime factor of i. That way each composite is marked exactly once, by its smallest prime factor, which gives O(N) time. As a bonus it records the smallest prime factor of every number, which makes factorising many numbers quick.
How would you check whether one very large number is prime?
For a single number the sieve is the wrong tool, because it does work for every number below it. Trial division up to the square root is fine for numbers up to about 10 to the power 12. For much larger numbers we use the Miller-Rabin test, a fast check based on modular arithmetic that is exact for 64-bit numbers with a fixed set of bases. In Java, BigInteger.isProbablePrime does this for us.
9Conclusion
We listed every prime up to N with the Sieve of Eratosthenes: walk i from 2, and whenever i is still unmarked it is prime, so cross out its multiples from i times i, stopping once i times i passes N. The numbers left unmarked are the primes. It takes O(N log log N) time and O(N) space, against O(N sqrt N) for testing each number. The clue to remember is the word all with a divisibility question: let each small number mark its multiples instead of testing every number on its own.
Open with
Let me confirm the requirements: primes up to and including N, returned in increasing order, an empty list for N below 2, and N small enough that an array of N booleans fits in memory.
Then, if they want more
Testing each number by trial division up to its square root works but costs O(N sqrt N), and it keeps relearning the same facts, such as dividing by 4 after 2 has already failed. Since the question asks for every number up to N, I will use the Sieve of Eratosthenes.
I keep a boolean array composite, all false at first. I walk i from 2 while i times i is at most N, using a long to avoid overflow.
If composite[i] is still false, i is prime, because any composite would have been marked by a smaller prime factor, and I mark its multiples starting at i times i, since smaller multiples were marked by smaller primes. Then I collect every index from 2 to N that is still false.
Each prime p does about N over p writes, which sums to O(N log log N) time, with O(N) space. For N too large for memory I would switch to a segmented sieve.
About this answer
- Last updated
- 15 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 17 times in that collection. How it is counted
- Official documentation
- ArrayList (Java 21), java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Print all prime numbers up to N.": https://scrivio-interview-library.netlify.app/data-structures/solutions/print-all-prime-numbers-up-to-n-4ef158/