您的位置:首页 > 其它

LeetCode 204. Count Primes

2016-07-09 16:36 387 查看
Problem: https://leetcode.com/problems/count-primes/

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

Thought:

SieveofEratosthenes

Code C++:(meet Runtime Error on test case 150000, which I haven't found the reason)

class Solution {
public:
int countPrimes(int n) {
if (n <= 1) {
return 0;
}
int nums
;
for (int i = 0; i < n; i++) {
nums[i] = 1;
}
nums[0] = 0;nums[1] = 0;
for (int i = 2; i * i <= n; i++) {
if (!nums[i]) {
continue;
}
for (int j = 2; i * j < n; j++) {
nums[i * j] = 0;
}
}
int solve = 0;
for (int i = 0; i < n; i++) {
solve += nums[i];
}
return solve;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: