Copy the code code as follows:
/**
* @author jxqlovedn
* Sieve method of Eratosthenes prime numbers, please refer to: http://zh.wikipedia.org/zh-cn/Sieve method of Eratosthenes prime numbers
*/
public class AratosternyAlgorithm {
public static void getPrimes(int n) {
if(n < 2 || n > 1000000) // The reason why the maximum value is limited to 1 million is because of JVM memory limitations. Of course, there are other flexible solutions that can be bypassed (such as bitmap method)
throw new IllegalArgumentException("Input parameter n is wrong!");
int[] array = new int[n]; // Assume that all initial numbers are prime numbers, and a certain number is a prime number, then its value is 0; for example, if the first number is a prime number, then array[0] is 0
array[0] = 1; // 0 is not a prime number
array[1] = 1; // 1 is not a prime number
//The following is the core process of screening
for(int i = 2; i < Math.sqrt(n);i++) { //Start from the smallest prime number 2
if(array[i] == 0) {
for(int j = i*i; j < n; j += i) {
array[j] = 1; // Mark this position as a non-prime number
}
}
}
//Print all prime numbers within n, 10 output per row
System.out.println(n + "The prime numbers within are as follows: ");
int count = 0; //The number of prime numbers currently output
int rowLength = 10; // Number of prime numbers output in each row
for(int i = 0; i < array.length; i++) {
if(array[i] == 0) {
if(count % rowLength == 0 && count != 0) {
System.out.println();
}
count++;
System.out.print(i + "/t");
}
}
}
public static void main(String[] args) {
getPrimes(99999);
}
}