easyNumber ProblemsJava

Generate the First N Prime Numbers

Print the first N prime numbers in ascending order.

Quick Answer

Start a candidate at 2 and keep a counter of how many primes you have found. Test each candidate for primality; when it is prime, print it and increase the counter. Stop as soon as the counter reaches N. Check divisibility only up to the square root to stay fast.

Problem Statement

Given a positive integer n, print the first n prime numbers in ascending order, separated by spaces. A prime number is an integer greater than 1 whose only divisors are 1 and itself.

Unlike printing primes below a fixed limit, here the limit is a count: you keep generating until you have collected exactly n primes.

Input: A single positive integer n — how many primes to generate.

Output: The first n primes in ascending order, separated by spaces.

Examples

Example 1
Input:  n = 5
Output: 2 3 5 7 11

The first five primes are 2, 3, 5, 7 and 11.

Example 2
Input:  n = 1
Output: 2

2 is the smallest and first prime number.

Constraints

  • 1 <= n <= 10000
  • The first prime is 2

Think Before You Code

Reveal the questions to ask yourself first
  • The task fixes how many primes you want, not the largest value — which loop fits that better?
  • How do you check whether a single candidate is prime?
  • Why can the primality check stop at the square root of the candidate?
  • What is the correct starting candidate, and which numbers can you skip?

Hints

Open them one at a time — try after each before revealing the next.

Hint 1
You do not know the upper bound in advance, so use a while loop that runs until your found-count reaches n.
Hint 2
Write an isPrime helper: return false for values below 2, otherwise test divisors from 2 up to sqrt(candidate).
Hint 3
Increment the counter only when a candidate is actually prime, and increment the candidate every iteration regardless.

Approach

Reveal the step-by-step approach

Drive the loop with a counter rather than a fixed range.

  1. Set count = 0 and candidate = 2.
  2. While count < n:
    • If candidate is prime, print (collect) it and increment count.
    • Increment candidate.
  3. isPrime(x) returns false for x < 2, then checks every i from 2 while i * i <= x; if any i divides x, it is not prime.

The counter guarantees you stop the instant you have exactly n primes, no matter how large the last one turns out to be.

Dry Run

Walk through the example step by step

Generating the first n = 5 primes:

candidate | prime? | count after
----------+--------+------------
2         | yes    | 1
3         | yes    | 2
4         | no     | 2
5         | yes    | 3
6         | no     | 3
7         | yes    | 4
8,9,10    | no     | 4
11        | yes    | 5  -> stop
Output: 2 3 5 7 11

Solution

Reveal the full Java solution
public class FirstNPrimes {
    public static boolean isPrime(int x) {
        if (x < 2) {
            return false;
        }
        for (int i = 2; i * i <= x; i++) {
            if (x % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static String firstNPrimes(int n) {
        StringBuilder sb = new StringBuilder();
        int count = 0;
        int candidate = 2;
        while (count < n) {
            if (isPrime(candidate)) {
                if (sb.length() > 0) {
                    sb.append(" ");
                }
                sb.append(candidate);
                count++;
            }
            candidate++;
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(firstNPrimes(5)); // 2 3 5 7 11
        System.out.println(firstNPrimes(1)); // 2
    }
}

Because the stopping condition is a count, a while loop is the natural fit — you cannot know in advance how far the candidate must travel to reach the nth prime. The i * i <= x bound keeps each primality test at O(sqrt x): if a number has a divisor larger than its square root, it must also have a matching one below it, so checking past the root is redundant.

Time: O(n * sqrt(p)) where p is the nth primeSpace: O(1) beyond the output

Common Mistakes

  • Starting the candidate at 1 and treating 1 as prime.
  • Incrementing the counter for every candidate instead of only for primes.
  • Using a for loop over a guessed upper bound and running out of primes for large n.

Edge Cases to Test

  • n = 1 should print just 2.
  • Even numbers above 2 must all be rejected by the primality test.
  • Large n (like 10000) still terminates because the counter keeps advancing.

Interview Follow-Ups

  • How would the Sieve of Eratosthenes speed this up when n is large?
  • Could you skip all even candidates after 2 to roughly halve the work?

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Explore the Java Full Stack program →
Chat with us