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.
一开始写了一个双层遍历的类型,具体如下:
class Solution {
public int countPrimes(int n) {
int count=0;
if(n<=2){return 0;}
for(int i=2;i<n;i++){
int flag=0;
for(int j=2;j<i;j++){
if(i%j==0){
flag=1;
break;
}
}
if(flag==0){
count++;
}
}
return count;
}
}
报错的原因是在数值较大的时候会超时Time Limit Exceeded
于是把第二层循环写成for(int j=2;j<=i/2;j++)范围从除以i/2到除以i/(i/2)=2还是超时
再继续改成for(int j=2;j<=Math.sqrt(i);j++)范围从除以i/2到除以根号2,不超时了,提交成功,但是运行速度不好。
具体代码如下:
class Solution {
public int countPrimes(int n) {
int count=0;
if(n<=2){return 0;}
for(int i=2;i<n;i++){
int flag=0;
for(int j=2;j<=Math.sqrt(i);j++){
if(i%j==0){
flag=1;
break;
}
}
if(flag==0){
count++;
}
}
return count;
}
}
参考网上的其他解题思路:
用一个布尔型数组,首先把0~n中不是prime的全部标出来,然后遍历一遍,遇到false的就count++,最后返回count就行。时间复杂度为O(n),(根号n*根号n),空间复杂度为O(n)。
public class Solution {
public int countPrimes(int n) {
if (n <= 1) {
return 0;
}
// 默认所有的元素值都会设置为false,从0到n-1一共有n个值
boolean[] notPrime = new boolean[n];
//初始化0和1为true,从2开始处理进行标注
notPrime[0] = true;
notPrime[1] = true;
for (int i = 2; i * i < n; i++) {
// 如果i是一个质数,则将i的倍数设置为非质数
// 如是i是一个合数,则它必定已经设置为true了,因为是从2开始处理的,所以代码里面就不用处理了
if (!notPrime[i]) {
for (int j = 2 * i; j < n; j += i) {
notPrime[j] = true;
}
}
}
// 统计质数的个数
int count=0;
for(int k=0;k<n;k++){
if(!flag[k]){
count++;
}
}
return count;
}
}