Algorithm for solving prime numbers

Source: Internet
Author: User
Tags square root

1. Loop nesting, the outer loop is from 1-1000 of the number I (1 excluded, which you should understand), the inner layer is the number I of the prime judgment.

2. Prime number: There is no other factor except 1 and itself. It can also be understood that except for 1 and itself, the remainder of the number is not 0.

3. So the inner loop is used from 2 to the square root of I (rounding) in order to find the remainder, because to the square root, and then increase the divisor, the quotient is less than the square root, equal to the divisor previously taken. So the square root after no longer forget.
1 classTest {2 3  Public StaticBoolean IsPrime (intN) {4      for(inti = 2; I <= math.sqrt (n); i++) { 5         if(n% i = = 0) {6         return false;7         } 8     }9     return true;Ten } One  A  Public Static voidMain (string[] args) { -  -  intLen = 1000; the  //1 is neither a prime nor a composite, and 2 is the smallest even prime. -   for(inti = 2; I <= Len; i + +) { -  if(Test.isprime (i)) { -System.out.print (i + "")); +              } -          } +     }  A}

Algorithm for solving prime numbers

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.