Count Prime

Count Prime

题目描述:

例子:

具体描述见LeetCode204

解题思路:

主要的思路是我们构建一个bool型的数组,假设全为true。在遍历到第i个数的时候,我们先判断这个数是否是小于sqrt(n)的结果,是的情况下,我们对这个找到的素数的整数倍位置都置为false;如果是true的情况下,在先前的数中已经判断过了所以无需再次判断。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
int countPrimes(int n) {
vector<bool> isPrime(n, true);
int primeCount = 0;
int upperBound = sqrt(n);
for (int i = 2; i < n; i++) { //Start from 2 since 1 * j == j, all the following numbers will be affected
if (isPrime[i-1]) {
primeCount++;
//When i > upper, i(bigger) * j(smaller) has already been checked, where i(bigger) == j(old) and i(smaller) == j(new)
//Eg. n == 11, 2 * 5 == 10 has been checked when i == 2 and j == 5, so when i == 5 > 3, no need to check 5 * 2 where i == 5 and j == 2.
if (i > upperBound)
continue;
for (int j = i; i * j < n; j++) { //j >= i, so that i(bigger) * j(smaller) has already been checked in previous loops
isPrime[i*j - 1] = false;
}
}
}
return primeCount;
}
};