Calculate all the prime numbers not greater than n. The better algorithm is the sieve method of elastostany: returns the range n of the values to be screened, and finds out the prime numbers. First use 2 to screen, that is, leave 2, remove the multiples of 2; then use the next prime number, that is, 3 to screen 3, and remove the multiples of 3; next, use the next Prime Number 5 sieve, leave 5, and remove the multiples of 5; continue to repeat ....... This algorithm is very fast, but its disadvantage is that it consumes memory. Theoretically, all the numbers in the n range must be stored in the memory. This can be optimized: you only need to assign one digit to each number. After all, you only need to know whether this number is a prime number. Here we can further optimize it: we only need to save all the odd numbers (even numbers except 2 are not prime numbers). Therefore, we can use the memory of n/16 to implement this algorithm: [cpp] inline bool getBit (char * arr, size_t pos) {return (arr [pos/8] & (1 <pos % 8 ))! = 0;} inline void setBit (char * arr, size_t pos) {arr [pos/8] |=( 1 <pos % 8);} void printPrimes (size_t n) {if (n <2) return; char * arr = new char [(n + 15)/16]; memset (arr, 0, (n + 15)/16 ); // printf ("2"); size_t total = 1; // 2 for (size_t curNum = 3; curNum <= n; curNum + = 2) {if (getBit (arr, curNum/2) continue; ++ total; // printf ("% lu", curNum); for (uint64 pos = (uint64) curNum * curNum/2; pos <N/2; pos + = curNum) {setBit (arr, pos) ;}} printf ("\ ntotal number: % lu \ n", total ); delete [] arr;} In my pc, it takes just one second to calculate the prime number in 0.1 billion, and only needs to allocate 6 MB of memory.