Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a Java method that returns all prime numbers up to n, where n can be 10,000,000. Explain the algorithm, its complexity, the memory you need, and one overflow bug that is easy to introduce.

We use the Sieve of Eratosthenes: a boolean[] composite of size n + 1, and for every i from 2 while i * i <= n, if i is not yet marked, mark i * i, i * i + i, and so on as composite; whatever stays unmarked is prime. It runs in O(n log log n) time and needs about n bytes, 10 MB for 10 million, or n / 8 bytes with a BitSet. Starting at i * i is safe because smaller multiples were already marked by smaller primes, and the easy bug is that i * i overflows int for i above 46,340, so we compute it as a long or test i <= n / i.

Why this question is asked

Generating primes up to a limit comes up in coding interviews and in real work such as test data generation, hash table sizing and cryptography exercises. With n as large as 10 million, testing each number separately is too slow, so the question checks whether we know the sieve, can explain why it is fast, and can write it without the overflow and boxing mistakes that make a correct algorithm fail at scale. In this answer, we will see why trial division is too slow, build the sieve step by step, explain the i * i starting point, work out the time and memory, look at the overflow bug, and return the primes efficiently as an int[].

1Why Testing Each Number Is Too Slow

The simple approach checks every number k from 2 to n by trying to divide it by every d up to the square root of k. A prime k needs about sqrt(k) divisions, and for n = 10,000,000 there are 664,579 primes, each needing up to about 3,000 divisions, plus work for composites. That adds up to billions of divisions, and division is a slow instruction. The sieve avoids division entirely: instead of asking 'does anything divide k?', it walks forward through the multiples of each prime and crosses them out.

2Building the Sieve Step by Step

We create an array where composite[k] will become true if k has a divisor other than 1 and itself. We start at 2. If 2 is not marked, it is prime, and we mark all its multiples. Then 3 is not marked, so it is prime, and we mark its multiples. 4 is already marked, so we skip it. Each time we reach an unmarked number, it is a prime, because no smaller prime divides it. We only need to process i while i * i <= n, because every composite up to n has a prime factor no larger than sqrt(n); after that point, every remaining unmarked number is prime.

Java
static boolean[] sieve(int n) {
boolean[] composite = new boolean[n + 1]; // all false: assume prime
for (int i = 2; (long) i * i <= n; i++) {
if (composite[i]) continue; // not a prime, skip
for (int j = i * i; j <= n; j += i) { // i * i fits: i <= sqrt(n)
composite[j] = true;
}
}
return composite; // primes: k >= 2 with !composite[k]
}
boolean[] c = sieve(30);
for (int k = 2; k <= 30; k++) if (!c[k]) System.out.print(k + " ");
// 2 3 5 7 11 13 17 19 23 29
Step throughThe sieve for n = 30
  1. i = 2: primemark 4, 6, 8, ..., 30
  2. i = 3: primemark 9, 12, 15, ..., 30
  3. i = 4: already markedskip
  4. i = 5: primemark 25, 30
  5. i = 6: 36 > 30stop the outer loop
  6. Unmarked numbers from 22 3 5 7 11 13 17 19 23 29

6 steps in order. Play them, or step through them one at a time.

Each prime starts crossing out at its own square.

3Why Starting at i * i Is Correct

When we reach prime i, the multiples smaller than i * i are 2i, 3i, ..., (i - 1) x i. Each of these has a factor smaller than i, namely 2, 3 and so on up to i - 1, and every such number has a prime factor smaller than i. That smaller prime was processed earlier and has already marked the number. For example, when i = 5, the multiples 10, 15 and 20 were marked by 2 and 3, so the first new multiple is 25. Starting at i * i saves work and, more importantly, gives the outer loop its stopping rule: if i * i > n, prime i has nothing left to mark.

4Time and Memory

For each prime p up to sqrt(n), the inner loop marks about n / p numbers. The sum of n / p over primes up to n grows like n log log n, which is a famous result about the sum of reciprocals of primes. log log n is tiny: for n = 10 million, ln ln n is about 2.8. So the sieve is practically linear and runs in tens of milliseconds for 10 million.

Memory is the array. A boolean[] uses one byte per element on HotSpot, so 10,000,001 elements take about 10 MB. A java.util.BitSet packs 64 flags into each long, so it needs n / 8 bytes, about 1.25 MB, at the cost of a shift and mask per access. A further common trick is to store only odd numbers, since 2 is the only even prime, which halves memory again. For n in the billions, a segmented sieve processes the range in blocks that fit in the CPU cache.

Memory for n = 10,000,000
RepresentationBytes per numberTotal
boolean[]1about 10 MB
BitSet (long[] words)1/8about 1.25 MB
BitSet, odd numbers only1/16about 0.6 MB
List<Integer> of 664,579 primesabout 16 to 20 per primeabout 11 to 13 MB

5The Overflow Bug That Is Easy to Introduce

Many sieves are written with for (int i = 2; i * i <= n; i++). That looks fine, but i * i is computed in int arithmetic. Once i exceeds 46,340, i * i is larger than Integer.MAX_VALUE and wraps to a negative number, which is always <= n, so the loop condition is never false at the right moment. For n = 10 million, i only reaches about 3,163, so the bug stays hidden; it appears only when n is close to Integer.MAX_VALUE, and the symptom is an ArrayIndexOutOfBoundsException or a loop that runs far too long.

Java
int i = 46_341;
System.out.println(i * i); // -2147479015: overflowed
System.out.println((long) i * i); // 2147488281
// Safe loop conditions:
// for (int i = 2; (long) i * i <= n; i++)
// for (int i = 2; i <= n / i; i++)

Both fixes are standard. Casting one operand to long makes the multiplication 64-bit. Writing the condition as i <= n / i uses division to avoid the multiplication entirely. Inside the loop, j = i * i is safe because i has already been checked to satisfy i * i <= n, but j += i can still overflow when n is near Integer.MAX_VALUE, so for that range the inner loop should use a long counter too.

6Returning the Primes Without Boxing

Returning a List<Integer> of 664,579 primes boxes each one into an Integer object, which costs memory and garbage collection. A better approach counts the primes first, allocates an int[] of exactly that size, and fills it. The count pass is cheap, a single scan of the array.

Java
static int[] primesUpTo(int n) {
if (n < 2) return new int[0];
boolean[] composite = sieve(n);
int count = 0;
for (int k = 2; k <= n; k++) if (!composite[k]) count++;
int[] primes = new int[count];
for (int k = 2, idx = 0; k <= n; k++) if (!composite[k]) primes[idx++] = k;
return primes;
}
System.out.println(primesUpTo(10_000_000).length); // 664579
System.out.println(primesUpTo(1).length); // 0

The int[] takes about 2.6 MB for 664,579 primes, compared with over 10 MB for the boxed list, and iterating it is much faster because the values are contiguous in memory.

7Follow-up questions

How would you check primality of a single 64-bit number?

A sieve to 2^63 is impossible, and trial division up to sqrt(n), about 3 billion, is far too slow. The standard answer is the Miller-Rabin test, which is deterministic for all 64-bit numbers when run with a known fixed set of bases, such as the first twelve primes. In Java, BigInteger.valueOf(n).isProbablePrime(certainty) uses Miller-Rabin and is fine for occasional checks; for many checks, a hand-written Miller-Rabin with Math.multiplyHigh or modular multiplication in long avoids BigInteger allocation.

Can the sieve be parallelised?

Yes, with a segmented sieve. First sieve the primes up to sqrt(n) once, then split the range into blocks and let each thread mark multiples of those base primes in its own block. Each block fits in cache, which also makes the single-threaded version faster for very large n.

Why not use a BitSet by default?

A BitSet saves 8x memory, which matters for large n or memory-limited services, but each access needs a shift and a mask, so a boolean[] is often a little faster for n around 10 million, where 10 MB is affordable. It is a trade-off worth measuring.

8Conclusion

In this answer, we generated primes up to 10 million with the Sieve of Eratosthenes, marking multiples of each prime starting from i * i, which is safe because smaller multiples were already marked by smaller primes. It runs in O(n log log n) time and needs about 10 MB as a boolean[] or about 1.25 MB as a BitSet. We saw that i * i overflows int above 46,340 and fixed the loop condition with long arithmetic or i <= n / i, and we returned the primes as an int[] sized by counting first instead of a boxed List<Integer>.

What to say in the interviewAbout 100 seconds aloud

Open with

I would use the Sieve of Eratosthenes. I allocate a boolean array called composite of size n plus one, all false. Then for i from two while i times i is at most n, if i is not marked it is prime, and I mark i times i, i times i plus i, and so on up to n as composite.

Then, if they want more

At the end every unmarked number from two upwards is prime. I start at i squared because any smaller multiple of i has a smaller prime factor and was already marked, and that is also why the outer loop can stop at the square root of n.

The time is O(n log log n), which is almost linear, and for ten million it runs in milliseconds. Memory is one byte per number with a boolean array, about ten megabytes, or n over eight bytes with a BitSet, about 1.25 megabytes, and storing only odd numbers halves that again.

The easy overflow bug is writing the loop as i times i less than or equal to n with ints: above 46,340, i squared overflows to a negative number and the condition stays true, so I write it as long i times i, or as i less than or equal to n divided by i.

Finally, I would return the primes as an int array, counting them first and then filling it, instead of a List of Integer, which would box 664,579 values.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
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 "Write a Java method that returns all prime numbers up to n, where n can be 10,000,000....": https://scrivio-interview-library.netlify.app/java/coding-problems/8fe7e500a7/