题目链接https://leetcode.com/problems/count-primes/
public class Solution {
public int countPrimes(int n) {
int count = 0;
for(int i=2;i<=n;i++){
boolean isPrime = true;
for(int j=2;j<=Math.sqrt(n);j++){
if(n%j==0){
isPrime = false;
break;
}
}
if(isPrime)count++;
}
return count;
}
}
上面是我经过提示才写出来的最开始部分,之前可能判断的边界条件是j<=n经过优化之后是j<=n/2,后来才变为上面所示的部分。
public class Solution {
public int countPrimes(int n) {
if(n==0||n==1)return 0;
int count = 0;
boolean[] mark = new boolean[n+1];
for(int p=2;p<=Math.sqrt(n);p++){
if(!mark[p]){
mark[p] = true;
for(int i=0;p*p+i*p<=n;i++){
mark[p*p+i*p] = true;
}
count++;
}
}
for(int i=2;i<n;i++){
if(!mark[i])count++;
}
return count;
}
}