[Leetcode] Count Primes

Source: Internet
Author: User

Description:

Count the number of prime numbers less than a non-negative number, n

Hint:the number n could is in the order of 100,000 to 5,000,000.

Click to show more hints.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Ernie Eratosthenes Sieve method. Starting from the first prime number to remove its multiples, then the next one is not removed must be a prime, repeat the above process. Specific can be seen.

But the submission has found a timeout! Time Out!!!! Isn't that a positive solution? So after a meal optimization, finally AC dropped.

1 classSolution {2  Public:3     intCountPrimes (intN) {4vector<BOOL> P (N,true);5         //Remove all even numbers outside of 26          for(inti =4; I < n; i + =2) P[i] =false; 7         //The previous step has removed even, so i + = 2,j + = 2 can be used here8          for(inti =3; I * i < n; i + =2) {         9             if(P[i]) for(intj =3; I * j < n; J + =2) {TenP[i * j] =false; One             } A         } -         intCNT =0; -          for(inti =2; I < n; ++i)if(P[i]) + +CNT; the         returnCNT; -     } -};

However, actually spent 890ms, probably using the vector bar, and then tried again with the array, sure enough:

1 classSolution {2  Public:3     intCountPrimes (intN) {4         BOOL*p =New BOOL[n];5Memset (P,true,sizeof(BOOL) *n);6          for(inti =2; I * i < n; ++i) {7             if(P[i]) for(intj =2; I * j < n; ++j) {8P[i * j] =false;9             }Ten         } One         intCNT =0; A          for(inti =2; I < n; ++i)if(P[i]) + +CNT; -         Delete []p; -         returnCNT; the     } -};

Without any optimization, it only took 400ms, optimized as long as 170ms. Therefore, the difference in efficiency between the vector and the original array is evident in this question.

[Leetcode] Count Primes

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.