반응형
https://leetcode.com/problems/count-primes/submissions/
Count Primes - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
에라토스테네스의 체로 품
Think of the array's index like the key in the Hash. Define the boolean array and let the index as the integer less than n, and let the value of the array have boolean value.
int countPrimes(int n) {
int answer = 0;
vector<bool> isPrime(n+1, true);
isPrime[1] = false;
if (n == 1|| n==2){
return answer = 0;
}
if(n==3){
return answer = 1;
}
if (n==4) return answer = 2;
for(int i = 2; i <= sqrt(n); i++){ // O(n^(3/2))
if(isPrime[i]){
for(int j = i+i; j < n; j+=i){
isPrime[j]=false;
}
}
}
for(int i = 1; i < n; i++){
if(isPrime[i]){
answer++;
}
}
return answer;
}
반응형
'알고리즘_개념 및 문제풀이 ' 카테고리의 다른 글
리트코드/leetcode/배열 중복 제거/remove-duplicates-from-sorted-array (0) | 2019.10.05 |
---|---|
https://leetcode.com/problems/4sum/ (0) | 2019.09.28 |
Leetcode/jewels and stones/해시/Hash (0) | 2019.09.28 |
백준온라인저지(BOJ)/#9613//GCD(최대공약수)/C++/유클리드 호제법(Euclidean Algorithm) (0) | 2019.08.04 |
완전 탐색- 재귀함수를 이용한 완전 탐색(기본 개념) (0) | 2019.06.07 |