Description:
Count the number of prime numbers less than a non-negative number, n.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Statistical prime: Given a nonnegative integer n, the number of prime numbers smaller than n is counted. This problem at first glance is very simple, is to write a function to determine whether it is a prime number, and then the N-cycles. However, the test data will appear very large n, and the normal method will run the timeout. The traditional method of determining whether a number is prime is the time complexity of O (log2n) (compared with the square root n), and the time complexity of the n number is multiplied by N.
Leetcode the topic as simple, because he gave a series of hints and gave another algorithm, with more memory in exchange for shorter time. The overall idea is to generate an array of n (n input) elements (initialized to 0), start from 4 to N to end all the composite set to 1, and then 2 times the group, encountered as 0 element count plus one. I first stuck the code below, can not see the leetcode of the topic link https://leetcode.com/problems/count-primes/above has a complete hints
1 classSolution {2 Public:3 voidSetflag (vector<int>& VEC,intNintmax) {4 Long Long intt = N;//convert growth long shaping, otherwise n squared may overflow5 for(Long Long inti = t * t; i < Max; i + =N) {6Vec[i] =1;7 }8 }9 intCountPrimes (intN) {Ten if(N <3)return 0; One //int *vec = (int *) malloc (sizeof (int) * n); Avector<int> Vec (n +1,0); - for(inti =2; I < n; i++) { - Setflag (VEC, I, n); the } - intCount =0; - for(intj =2; J < N; J + +) { - if(!Vec[j]) { +count++; - } + } A returncount; at } -};
View Code
204 Count Primes