Today's applet is the herados screening-find all prime numbers smaller than integer n
The basic idea of the errado screening is: Starting from the smallest prime number 2, we first circle 2 and then remove the multiples of 2. Find the next uncircled number 3 and remove the multiple of 3. Find the next uncircled number 35, remove the multiples of 5, and so on until the square root of N does not need to be removed. The remaining number to be circled is the prime number to be searched.
1 package determines the prime number; 2 3 Import Java. util. arraylist; 4 5 public class Shai {6 public static void main (string [] S) {7 system. out. println (findprime (100); 8} 9 Private Static arraylist <integer> findprime (int n) {10 // 1, first, assign 11 int [] num = new int [n + 1] to the number in the array; // to save n numbers and do not conflict with the badge, the array size is n + 1. In this way, we only use the array 12 for (INT I = 0; I <= N; I ++) labeled as 1) 13 num [I] = I; 14 // 2, remove the sum in sequence, that is, set the sum to zero 15 int end = (INT) math. SQRT (n); 16 for (INT I = 2; I <= End;) {17 for (Int J = I * 2; j <= N; j + = I) {// note that J starts from I * 2 18 num [J] = 0; 19} 20 I = next (Num, I); 21} 22 // 3, finally, traverse the array and put the number that is not set to zero, that is, the prime number, into the list. list23 arraylist <integer> Sushu = new arraylist <integer> () is returned (); 24 For (INT I = 2; I <n; I ++) {25 if (Num [I]! = 0) {26 Sushu. add (Num [I]); 27} 28} 29 return Sushu; 30} 31 // find the next unset number 32 Private Static int next (INT [] AA, int I) {33 while (AA [++ I] = 0) {34} 35 return I; 36} 37}
Daily Record-