标签:
Description:
Count the number of prime numbers less than a non-negative number, n.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
解析:大于1的自然数,该自然数能被1和它本身整除,那么该自然数称为素数。
方法一:暴力破解,时间复杂度为O(N^2)
代码如下:
public class Solution {
public int countPrimes(int n) {
if(n<=2) return 0;
int num=0;
for(int i=2;i<n;i++)
if(isPrime(i))
num++;
return num;
}
public boolean isPrime(int i){
for(int j=2;j<i;j++){ //或者for(int j=2;j<=i/2;j++); 或者for(int j=2;j*j<i;j++);
if(i%j==0)
return false;
}
return true;
}
}
运行结果:超时,时间复杂度O(N^2)

方法2:素数的倍数均排除掉。
代码如下:
public class Solution {
public int countPrimes(int n) {
if(n<=2) return 0;
boolean []isPrime=new boolean[n];
int sum=0;
for(int i=2;i<n;i++){
isPrime[i]=true;
}
for(int i=2;i<n;i++){
if(isPrime[i]){
for(int j=2;j*i<n;j++){
isPrime[j*i]=false;
}
}
}
for(int i=2;i<n;i++){
if(isPrime[i]==true)
sum++;
}
return sum;
}
}
运行结果:时间复杂度O(n).

(easy)LeetCode 204.Count Primes
标签:
原文地址:http://www.cnblogs.com/mlz-2019/p/4680999.html