Space-saving sieve Prime Number Method

Source: Internet
Author: User

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.

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.