Daily Record-

Source: Internet
Author: User

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-

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.