Copy Code code as follows:
/**
* @author Jxqlovedn
* Eratosthenes prime number Screening method, please refer to: http://zh.wikipedia.org/zh-cn/Eratosthenes Sieve method
*/
public class Aratosternyalgorithm {
public static void Getprimes (int n) {
if (N < 2 | | | n > 1000000) The maximum value is limited to 1 million because of the JVM memory limit, there are other flexible schemes that can be bypassed (e.g. bitmap method)
throw new IllegalArgumentException ("Input parameter n Error!") ");
int[] array = new Int[n]; Assuming that all the initial numbers are prime, and a number is a prime, the value is 0; For example, the first number is prime then array[0] is 0
Array[0] = 1; 0 is not prime
ARRAY[1] = 1; 1 is not prime
The following is the filtering core process
for (int i = 2; i < MATH.SQRT (n); i++) {//starting from the minimum prime number 2
if (array[i] = = 0) {
for (int j = I*i J < n; j + = i) {
ARRAY[J] = 1; Identifies the location as a non prime
}
}
}
Print all prime numbers within N, 10 outputs per row
SYSTEM.OUT.PRINTLN (n + ") within the prime number as follows:";
int count = 0; Number of prime numbers that are currently being exported
int rowlength = 10; Number of primes per line output
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);
}
}