Prime Numbers up to N
Problem
Read an integer n and print all prime numbers from 1 to n in ascending order on one line, separated by a space. If there is no prime, print an empty line.
Constraints
- 0 <= n <= 10^6 (10^4 for the simple version)
Examples
Input
30
Output
2 3 5 7 11 13 17 19 23 29
Solutions
We assume every number is prime. Then we cross out all multiples of each prime we find. What is left are the primes. Each number is crossed out only a few times, so this is much faster.
/*
* Problem : List all prime numbers from 1 to n.
* Input : One integer n.
* Output : The primes on one line, separated by a space (an empty line if there is none).
* Approach: Cross out the multiples of each prime (Sieve of Eratosthenes).
* Time : O(n log log n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int limit = new Scanner(System.in).nextInt();
StringBuilder result = new StringBuilder();
// Step 1: Make a list of true/false values. isPrime[i] tells if the number i is still a prime candidate.
boolean[] isPrime = new boolean[limit + 1];
for (int number = 2; number <= limit; number++) {
isPrime[number] = true;
}
// Step 2: Go through the numbers from 2 up to the square root of the limit.
for (int number = 2; (long) number * number <= limit; number++) {
// Step 3: If the number is still a candidate, it is prime. Cross out its multiples.
if (isPrime[number]) {
// Step 4: Start at number * number. Smaller multiples were crossed out by smaller primes already.
for (int multiple = number * number; multiple <= limit; multiple += number) {
isPrime[multiple] = false;
}
}
}
// Step 5: All numbers that are not crossed out are prime. Write them down.
for (int number = 2; number <= limit; number++) {
if (isPrime[number]) {
if (result.length() > 0) {
result.append(" ");
}
result.append(number);
}
}
System.out.println(result);
}
}
Hints (2)
- A multiple of 2 can not be prime. What about the multiples of 3?
- You only need to cross out multiples of primes up to the square root of n.