Several algorithms for finding prime numbers

Source: Internet
Author: User
Tags integer division square root

Http://blog.sina.com.cn/s/blog_622e77cc0100n5lm.html

1, according to the definition of prime numbers to seek
Prime number definitions: natural numbers (excluding 1), which can be divisible by only 1 or itself, are called prime numbers.
Its definition can be used to iterate over the number divided by each natural number smaller than it (greater than 1), which is not prime if it can be divisible by it.
The corresponding code is:

        /// <summary>        ///output all prime numbers from 2 to Max/// </summary>        /// <param name= "Max" ></param>         Public Static voidPrime (intmax) {            BOOLFlag =false; intCount =0;  for(inti =2; I <= Max; i++) {flag=IsPrime (i); if(flag) {Console.Write ("{0,3}", i); Count++; if(Count%8==0) {Console.WriteLine (); }                }            }        }        /// <summary>        ///determine if the number entered is prime/// </summary>        /// <param name= "n" ></param>        /// <returns></returns>         Public Static BOOLIsPrime (intN) {BOOLFlag =true; if(N <2)            {                Throw NewArgumentOutOfRangeException (); }             for(inti =2; I <= N-1; i++)            {                if(n% i = =0) {flag=false;  Break; }            }            returnFlag; }


2, using a theorem-if a number is composite, then its minimum factorization is certainly less than equal to his square root. For example: 50, the minimum factorization is the open root of 2,2<50
Another example: 15, the minimum factorization is the open root of 3,3<15
Composite is the natural number corresponding to prime numbers. A natural number greater than 1 if it is not a composite, then it is prime.
The above theorem is that if a number can be divisible by its smallest factorization, it must be composite, that is, not prime. So judging whether a number is a prime, just to determine whether it can be less than the number of all after the opening and after the integer division, so that the operation will be much less, so the efficiency is much higher.
The corresponding code is:

Just make a change to the previous prime number.

        /// <summary>        ///determine if the number entered is prime/// </summary>        /// <param name= "n" ></param>        /// <returns></returns>         Public Static BOOLIsPrime (intN) {BOOLFlag =true; if(N <2)            {                Throw NewArgumentOutOfRangeException (); }            intMax =Convert.ToInt32 (Math.floor (MATH.SQRT (n)));  for(inti =2; I <= Max; i++)            {                if(n% i = =0) {flag=false;  Break; }            }            returnFlag; }

3.Sieve method for prime number, the most efficient, but will be more waste of memory
Start by creating a Boolean array that stores the prime numbers you want to determine in a range of natural numbers, for example, if you want to output a prime number less than 200, you need to create a Boolean array with a size of 201 (to create 201 storage locations to make the array position the same size). Initialized to True.
Secondly, the first prime number in the second method (in this case, 2), and then will be a multiple of 2 is all false (except 2), that is, 2, 4, 6, 8 ... The position is set to false. Then a multiple of 3 is set to False (except 3), until 14 (14 is the open square of 200), so that the position is not prime number is false, the rest is prime, and pick the true print out on the line.
The corresponding code is:
Boolean[] Printprime (int range) {
Boolean[] Isprime=new boolean[range+1];
ISPRIME[1]=FALSE;//1 is not prime.
Arrays.fill (IsPrime, 2,range+1,true);//Full Set to true (position greater than or equal to 2)
int n= (int) math.sqrt (range);//Open radical for range
for (int i=2;i<=n;i++)//note need to be less than or equal to n
if (Isprime[i])//view is not already set false too
for (int j=i;j*i<range;j++)//will be a multiple of position set to False
Isprime[j*i]=false;
Return isprime;//returns a Boolean array
}

Several algorithms for finding 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.