Various algorithms for printing prime numbers

Source: Internet
Author: User

The algorithm for printing prime numbers should be a classic problem in computer programming. Here I want to show you some methods. I believe these methods will inspire your programming. Pay attention to the following points,

  • The actual application is very different from the teaching application.
  • You can focus on the method that uses the compilation instead of the runtime.
Example of a textbook

First, give a textbook example. The example below should be the example of the best algorithm complexity in textbooks (at least I taught science in College. The idea is very simple. First, write a function isprime () to determine whether it is a prime number, and then call the isprime () function from 1 to n to check it. The core algorithm is to check whether it is a prime number. It simply uses the number of root openings from 2 to N as the divisor. The complexity of this algorithm is almost O (N * log (N). It looks good, but it is not economical.

# Include <iostream> <br/> using namespace STD; </P> <p> bool isprime (INT nr) <br/> {<br/> for (INT d = 2; (D * D) <(NR + 1); ++ d) {<br/> If (! (NR % d) {<br/> return false; <br/>}< br/> return true; <br/>}</P> <p> int main (INT argc, char * const argv []) <br/> {<br/> for (INT I = 0; I <50; ++ I) {<br/> If (isprime (I )) {<br/> cout <I <Endl; <br/>}< br/>}

Good Algorithms

We know that if our algorithm is written as a linear algorithm, that is, O (N), it is good, but the best is the O (log (N) algorithm, this is a logarithm-level algorithm. The famous binary search algorithm is O (log (n.Generally, O (log (N) algorithms are based on exclusion.
. Therefore, the algorithm for finding prime numbers can use the exclusion method. The complexity of this algorithm is as follows:O
(N (log (logn ))).

Example: print the prime number within 30

1. initialize the following list.

 2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

2. Extract the first number (2) and remove all the numbers that can be divisible by 2.

 2  3     5     7     9    11    13    15    17    19    21    23    25    27    29

3. Take the second number (3) and remove all numbers that can be divisible by 3.

 2  3     5     7          11    13          17    19          23    25          29

4. Take the third number (5), because 4 has been removed, and then remove all the numbers that can be divisible by 5.

 2  3     5     7          11    13          17    19          23                29

The next number is 7, but the square of 7 is 49, which is greater than 30, so we can stop the calculation. The remaining number is all the prime numbers.

Practical Algorithms

In practice, we usually do not use the above two algorithms, because they are academic algorithms. The actual algorithm is that I calculate the prime number in advance, put it in a file, and then read the file at the startup of the program, instead of reading the file every time you call it during runtime), read the file and print it out. If you need to search, binary search or hash table search will greatly improve the performance. Of course, this method consumes more space than the first two, but you can have the time complexity of O (log (N) or O (1.

So I want to remind you here --The actual and theoretical methods are very different.
Never read as a nerd. In the world of game programming, a large amount of data is not computed, but written in files. For example, the flame effect and the running action of a character are all written in the file beforehand.

Use the compilation instead of running

The following is an example.
) You need to note that this is an advanced usage. The mode is used to calculate the prime number during compilation, rather than during runtime. This technology uses the C ++ compiler to Process Template features to generate desired results. This method is technically cool, but not necessarily practical. Here we just want to demonstrate this usage. This is the most basic usage of C ++.

Please refer to the following two template classes. The first template uses recursion to check whether it is a prime number, and the second method is a recursive exit condition (when n = 1). For template overloading, see related C ++ books.

Template <int N, int d = n-1> <br/> struct isprime {<br/> Enum {<br/> result = (N % d) & isprime <n, D-1 >:: result <br/> }; </P> <p> template <int n> <br/> struct isprime <n, 1 >{< br/> Enum {<br/> result = true <br/> };

Therefore, through this template, we can use the following code to check whether it is a prime number:

If (isprime <3 >:: result) <br/> cout <"guess what: 3 is a prime! ";

Next, we need to specify a prime number in the interval. Therefore, we need to design our print template.

Template <int N, bool isprime> <br/> struct printifprime {<br/> static inline void print () {}< br/> }; </P> <p> template <int n> <br/> struct printifprime <n, true >{< br/> static inline void print () {<br/> STD: cout <n <Endl; <br/>}< br/> };

From the code above, we can see that we did nothing but output the second one. Note that there is a true parameter in the second template, it indicates the determination of the prime number. So we can give the following code to try to print the prime number in a range :(Please do not compile !!
This will bring the compiler into an infinite loop, because printprimes will continuously call itself and never stop)

Template <int N, int max> <br/> struct printprimes {<br/> static inline void print () <br/>{< br/> printifprime <n, isprime <n >:: result >:: print (); <br/> printprimes <n + 1, Max >:: print (); <br/>}< br/> };

To avoid this problem, you need to add a template class, as shown below. In this way, when N becomes Max, recursion ends.

Template <int n> <br/> struct printprimes <n, n >{< br/> static inline void print () {<br/> printifprime <n, isprime <n >:: result >:: print (); <br/>}< br/> };

Finally, let's take a look at the final call:

Int main (INT argc, char * const argv []) <br/>{< br/> printprimes <2, 40 >:: print (); <br/> return 0; <br/>}

This method is Nb, but there are two problems:

  • Compilation Time is relatively high.
  • You cannot enter the value of Max at runtime.

However, I believe this method will start many of your programming ideas.

Of course, there is also the previously mentioned Regular Expression for checking prime numbers.
"

(Full text)

Source of the original article (Click here)

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.