easyNumber ProblemsJava

Print All Prime Numbers Between 1 and N

Print every prime number from 2 up to a given upper limit N.

Quick Answer

Loop through every number from 2 to N and print it if it is prime. To test a candidate, check whether any value from 2 up to its square root divides it evenly; if none does, it is prime. This is a primality test wrapped in an outer loop over the range.

Problem Statement

Given an upper limit N, print every prime number from 2 up to and including N, separated by spaces. A prime has no divisors other than 1 and itself, so 2, 3, 5, 7 are printed for N = 10.

Iterate over each candidate in the range and print those that pass a primality test. For each candidate, testing divisors only up to its square root keeps the work small.

Input: A single integer N (the inclusive upper bound).

Output: The prime numbers from 2 to N, separated by single spaces, on one line.

Examples

Example 1
Input:  10
Output: 2 3 5 7

Between 2 and 10 the primes are 2, 3, 5 and 7; 4, 6, 8, 9, 10 are composite.

Example 2
Input:  20
Output: 2 3 5 7 11 13 17 19

All primes up to 20 are listed in order.

Constraints

  • 1 <= N <= 2,147,483,647 (though large N produces long output)
  • If N < 2 there are no primes to print

Think Before You Code

Reveal the questions to ask yourself first
  • How will you reuse a single-number primality test for every value in the range?
  • Where should the loop start, given that 0 and 1 are not prime?
  • How do you keep the output on one line with clean spacing between primes?

Hints

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

Hint 1
Write a helper that answers is this one number prime, then call it for every value from 2 to N.
Hint 2
Inside the helper, test divisors only from 2 up to the square root of the candidate.
Hint 3
Collect the primes in a StringBuilder so you can join them with single spaces and print one line.

Approach

Reveal the step-by-step approach

Loop over the range and print each value that passes a primality test.

  1. For each num from 2 to N:
    • Test whether num is prime by trial-dividing from 2 while i * i <= num.
    • If no divisor divides it, num is prime — append it to the output.
  2. Print the collected primes separated by single spaces.

The primality helper is the same square-root trial division used for a single number; here it simply runs once per candidate.

Dry Run

Walk through the example step by step

Building the list for N = 10:

num | prime? | reason
----+--------+-------------------------
2   | yes    | no divisor up to sqrt(2)
3   | yes    | 3 % 2 != 0
4   | no     | 4 % 2 == 0
5   | yes    | 5 % 2 != 0
6   | no     | 6 % 2 == 0
7   | yes    | 7 % 2, 7 % 3 != 0
8   | no     | 8 % 2 == 0
9   | no     | 9 % 3 == 0
10  | no     | 10 % 2 == 0

Output: 2 3 5 7

Solution

Reveal the full Java solution
public class PrimesUpToN {
    public static void printPrimes(int n) {
        StringBuilder sb = new StringBuilder();
        for (int num = 2; num <= n; num++) {
            if (isPrime(num)) {
                if (sb.length() > 0) {
                    sb.append(" ");
                }
                sb.append(num);
            }
        }
        System.out.println(sb.toString());
    }

    private static boolean isPrime(int n) {
        if (n < 2) {
            return false;
        }
        for (int i = 2; (long) i * i <= n; i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        printPrimes(10); // 2 3 5 7
        printPrimes(20); // 2 3 5 7 11 13 17 19
    }
}

The outer loop walks every candidate; the isPrime helper does the actual test using the square-root bound so each candidate costs only O(sqrt num). Using a StringBuilder and appending a space only before non-first entries keeps the output free of a trailing space.

Time: O(n * sqrt(n)) across the whole rangeSpace: O(1) beyond the output buffer

Common Mistakes

  • Starting the candidate loop at 0 or 1 and mistakenly printing them as primes.
  • Adding a separator before every prime, producing a leading space in the output.

Edge Cases to Test

  • N < 2 prints an empty line because there are no primes to list.
  • N = 2 prints just 2, the smallest prime.

Interview Follow-Ups

  • How would the Sieve of Eratosthenes speed this up for large N?
  • How would you print only the count of primes up to N instead of the primes themselves?

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