题目:
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
解答:
一开始用暴力解法,会出现超时
必须采用优化后的思路,要对这些数进行筛选。
- 用一个O(n)的数组来存储每一个数是不是质数
- 质数的倍数均为非质数,将筛选出来的非质数在数组中标为true,采用这种思路,找出所有的非质数。
class Solution {
public int countPrimes (int n) {
boolean[] array=new boolean[n];
int result=0;
for(int i=2;i<n;i++){
if(array[i]==false){//说明为质数
result++;//第一个数为2,一定为质数
//质数的倍数均不为质数
for(int j=2;j*i<n;j++){
array[j*i]=true;
}
}
}
return result;
}
}
同理,也可以用不断累加的方法。
- 将数组所有元素初始化为true
- 通过for循环找出所有不是素数的数,i 是一个质数,则 i 的平方一定不是质数,i^2 +i,i^2 + 2i…也一定不是素数
- 最后遍历数组,计算质数的数量
其中,并不需要对[2,n]的每一个数进行筛选,只需要对[2, n \sqrt{n} n]进行筛选,即可筛出所有不是素数的数。
class Solution {
public int countPrimes (int n) {
boolean[] array = new boolean[n];
int result = 0;
//将数组初始化为true
for (int i = 2; i < n; i++) {
array[i] = true;
}
//通过for循环找出所有非质数
for (int i = 2; i * i < n; i++) {
//若已被筛选为非质数,则continue
if (array[i]==false) {
continue;
}
else {
for (int j = i * i; j < n; j += i) {
array[j] = false;
}
}
}
//计算质数的数量
for (int i = 2; i < n; i++) {
if (array[i] == true) {
result++;
}
}
return result;
}
}