Count the number of prime numbers less than a non-negative number, n.
Example 1:
Input: n = 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Example 2:
Input: n = 0 Output: 0
Example 3:
Input: n = 1 Output: 0
Constraints:
- 0 <= n <= 5 * 106
문제 풀이:
에라토스테네스의 체를 사용
class Solution {
public:
int countPrimes(int n) {
int result = 0;
if(n<=2){return result;}
vector<int> v(n,0);
for(int i=2; i<n; i++){
if(v[i] == 0){
result++;
for(int j = i; j<n; j += i){
v[j] = 1;
}
}
}
return result;
}
};
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 237] Delete Node in a Linked List (0) | 2020.11.27 |
---|---|
[leetcode 202] Happy Number (0) | 2020.11.25 |
[leetcode 217] Contains Duplicate (0) | 2020.11.25 |
[leetcode 172] Factorial Trailing Zeroes (0) | 2020.11.22 |
[leetcode 171] Excel Sheet Column Number (0) | 2020.11.22 |
댓글