您的位置:首页 > 其它

LeetCode - 204. Count Primes

2016-12-31 17:21 435 查看
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.

统计小于n的素数个数,直接枚举会超时。这里使用素数筛

class Solution {
public:
int countPrimes(int n) {
int *table = new int
;
table[2] = 0;

int count = 0;
for( int i = 2; i < n; i++ ) {
if( table[i] == 0 ) {
count++;
for( int j = i * 2; j < n; j += i ) {
table[j] = 1;
}
}
}

return count;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: