LeetCode/solutions/204. Count Primes.md
2020-07-04 20:04:42 +08:00

52 lines
2.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [204. Count Primes](https://leetcode.com/problems/count-primes/description/)
# 思路
## 思路一
不断循环,判断某个数是否是素数,判断思路:
对于大于1的整数n若n能被2、3...sqrt(n)中任意一个数整除则n不是素数否则是素数。
时间复杂度O(n^(3/2)), 空间复杂度O(1)
## 思路二*(厄拉多塞筛法)
求解有多少个小于某个数的素数的快速方法--厄拉多塞筛法([参考博客](https://blog.csdn.net/lisonglisonglisong/article/details/45309651))
西元前250年希腊数学家厄拉多塞(Eeatosthese)想到了一个非常美妙的质数筛法,减少了逐一检查每个数的的步骤,可以比较简单的从一大堆数字之中,筛选出质数来,这方法被称作厄拉多塞筛法(Sieve of Eeatosthese)。
具体操作:先将 2~n 的各个数放入表中然后在2的上面画一个圆圈然后划去2的其他倍数第一个既未画圈又没有被划去的数是3将它画圈再划去3的其他倍数现在既未画圈又没有被划去的第一个数 是5将它画圈并划去5的其他倍数……依次类推一直到所有小于或等于 n 的各数都画了圈或划去为止。这时,表中画了圈的以及未划去的那些数正好就是小于 n 的素数。
时间复杂度O(n)空间复杂度O(n)
# C++
## 思路一
``` C++
class Solution {
private:
bool isPrime(int n){
if(n < 2) return false;
for(int i = 2; i <= sqrt(n); i++)
if(n % i == 0) return false;
return true;
}
public:
int countPrimes(int n) {
int count = 0;
for(int i = 2; i < n; i++)
if(isPrime(i)) count++;
return count;
}
};
```
## 思路二
``` C++
class Solution {
public:
int countPrimes(int n) {
vector<bool>Prime(n + 1, true);
int res = 0;
for(int i = 2; i < n; i++){
if(Prime[i]){
res++;
for(int j = i; j <= n / i; j++) Prime[i*j] = false;
}
}
return res;
}
};
```