00:00

Problem Statement

Input/Output Examples

Visual Explanation

Crossing out starts at p × p, because smaller multiples of p were already removed by smaller primes. The outer loop can stop once p × p > n.

Approaches

The sieve shares work between numbers. Trial division tests each number on its own.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the upper limit. The sieve does about n log log n crossings; trial division can take up to √x divisions for every x.

Interview Tips and Recommended Approach

  • Start crossing at p × p. Smaller multiples are already crossed.
  • Stop the outer loop at √n. Larger primes have no new multiples to mark.
  • Know the memory cost. The sieve needs one boolean per number; a segmented sieve handles huge ranges.
  • Explain why 1 is not prime if asked; it has only one divisor.

Recommended Approach: Sieve of Eratosthenes

Why: it finds all primes in a range far faster than testing each number, with a few lines of code.