C # algorithm small problem - 2 - Get Prime Number

Title: (a) require that all primes in 1 ~ n.

         (B) to find all the prime numbers in a disorderly array of integers.

These two topics are the same solution, but the form has changed a bit. Here only (a) shows solution, (b) similar.

(1) a first solution

First, understand what is prime, prime numbers, also known prime number is divisible only by 1 and itself integers. Like 1,2,3,5,7 are prime numbers.

Understand the concept of prime numbers, the program is very easy to write out. To know whether a number x is prime, then just put all integers between 1 ~ x to x in addition, if there is such a number (except and x 1), which can be divisible by x (the remainder is 0), then x it is not a prime number, otherwise x is a prime number. This is the solution starting from Introduction. Then the following depends on how optimized.

 

In fact, we do not need to check all integer between 1 ~ x. Simply check number between 1 ~ [root X] on it. As for why, can be understood from the perspective of multiplication, division we do, in fact, in turn, is multiplication. We use 15 determines whether or not a prime number for example. In addition to the time when we are 3, 3 * 5 = 15. Therefore, while the determination 3 determines also another number 5. So we only need to check the root of x on it, when checking the root of x when x is also checked after root before.

The code (c #): 

         Private   static   void  PrintPrimes ( int  n-)
        {

             // output between all primes. 1 ~ n-, n-> =. 3
            Console.Write ( " . 1 2  " );
             int  I, J =  0 ;
             for  (I =  . 3 ; I < n-=; I = I +  2 )
            {
                 int  K = ( int ) Math.Sqrt (I);
                 for  (J =  2 ; J <= K; J ++)
                {
                     IF  ((I J%) ==  0 )
                    {
                         break;
                    }
                }

                 if (j > k)
                {
                    Console.Write(i.ToString() +  "   ");
                }
            }
        }

 

Note that the for loop in incremental interval is 2 instead of i ++. Because even number is certainly not a prime number, which increases the efficiency but also to some extent.

 

(2) The second solution

Since 1 ~ n is incremented and ordered, so there may be such a kind of solution: establishing an identity array of length n, and subscript 1 ~ n assigned to each number, each time a complete number is determined whether the prime number Thereafter, the reset flag corresponding to the number, a prime number 0, a non-prime number, and identify the location of all the multiples of the number 1, where in fact, eliminate some duplicate determination. Finally traversal identifies an array, the output of all prime numbers. But the cost of doing so is to open up some additional memory array as a logo. Of course, if the original array does not need to save, you can operate directly on the original array.

It sounds good, but in fact, not much faster than the first method. By looking at the operation time with Stopwatch, this solution is not how, only in a larger amount of data when its operating efficiency will be higher than on a way a little bit. I think it's because too many multiples of two (a method of increasing circulation step 2), so the method has removed a considerable part, then there is calculated multiples for each prime number, and then to identify the array assignment, also takes time .

The code (c #):

        private static void PrintPrimes2(int n)
        {
            int[] flags = new int[n];
            int j = 2;
            for (int i = 2; i <= n; i++)
            {
                if (flags[i - 1] == 0)
                {
                    if (!IsPrime(i))
                    {
                        flags[i - 1] = 1;
                    }

                    if (i <= n / 2)
                    {
                        j = 2;
                        while (i * j < n)
                        {
                            flags[i * j - 1] = 1;
                            j++;
                        }
                    }
                }
            }

            for (int k = 1; k < n; k++)
            {
                if (flags[k] == 0)
                {
                    Console.Write((k + 1).ToString() + " ");
                }
            }
        }

        private static bool IsPrime(int x)
        {
            if (x < 1)
            {
                throw new ArgumentException("Cannot be less than 1");
            }

            if (x < 3)
            {
                return true;
            }
            else
            {
                int k = (int)Math.Sqrt(x);
                int i = 2;
                for (; i <= k; i++)
                {
                    if (x % i == 0)
                    {
                        break;
                    }
                }

                if (i > k)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }


 (3) Third Method

If you can construct a good prime beforehand library, and it is easy to make an orderly at construction time. Then determine whether a number is prime, then direct binary search can quickly judge. To find the prime numbers within a range of n, then the number of all the library directly taken out can be less than n. So, how to construct a library prime it?

First, we know from a solution, it is determined whether a number is a prime number, and only an integer between 2 ~ Sqrt (n) modulo operation can be done. This determination process efficiency can be further improved. Imagine if belong integer 3,6,9 2 ~ Sqrt (n), we have to determine if an integer not divisible by 3, then certainly not be divisible by 6 and 9, these steps may be omitted. ! We can use at construction time has been prime number sequence structure

Suppose we have several well-established sequence: p1, p2, .. pn

now to judge pn + 1 whether it is a prime number, then only need (1, sqrt (pn + 1 )) in the range of all prime number sequence can be, not all the integers therebetween.

And this is clearly a prime number sequences p1, p2, .. pn is a subset included!

Library or number of codes is configured prime prime sequence as follows:

The method of creating the sequence of prime numbers between 2 ~ num and returns.

        static List<int> CreatePrimes(int num)
        {
            List<int> primes = new List<int>();
            primes.Add(2);
            primes.Add(3);

            for (int i = 5; i <= num; i += 2)
            {
                bool isPrime = true;

                // Why j starts from 1: Since i is an odd plus even number, it can only be odd, it can not be divided by 2, so the first set of primes
                 // element 2 would not have been calculated 
                for ( int j = 1 ; primes [J] * primes [J] <= I; ++ J)
                {
                    if (i % primes[j] == 0)
                    {
                        isPrime = false; 
                        break;
                    }
                }

                if (isPrime)
                {
                    primes.Add(i);
                }
            }

            return primes;
        }

Thus, if the operation is very frequently find prime numbers, then you can start to construct a large prime number sequence stored. Then a binary search to find a prime number is determined, taking the time sequence of prime numbers is also very convenient.

Have a blog to write algorithm for finding prime numbers is also good, see http://www.cnblogs.com/luluping/archive/2010/03/03/1677552.html .

 

Finally I would like to remind that it is, at present we are dealing with are int, of course, you can also change as a long, double. But after all, it is to have a range. If you give a string a fairly large number, far beyond the range of long, then how to judge it?

1. Construction yourself a new data structure to store, specifically I do not know. There was engaged in chip development people told me that this is not a problem.

2. Write your own method of operation to achieve the remainder, in fact, write code to achieve the division of primary school.

Write so it, we want to help.

 

 

Reproduced in: https: //www.cnblogs.com/CSharpSPF/archive/2012/04/04/2432105.html

Guess you like

Origin blog.csdn.net/weixin_34072159/article/details/93530998