【LeetCode】204. Count Primes
Count Primes
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.
每找到一个质数,将该质数所有整数倍排除。
如下图所示:
注意:
1、发现质数i时,需要排除的数从i*i开始而不是从i+i开始,因为小于i*i的数,都已经被小于i的质数排除了。
2、i*i时要做类型转换,不然会溢出。
class Solution { public: int countPrimes(int n) { int count = 0; if(n <= 2) return count; // none vector<bool> isPrime(n, true); for(int i = 2; i < n; i ++) { if(isPrime[i]) { count ++; // remove multiples of i for(long long j = (long long)i*i; j < n; j += i) isPrime[(int)j] = false; } } return count; } };