Leetcode 204. Count Primes
204. Count Primes
- Total Accepted: 71783
- Total Submissions: 285211
- Difficulty: Easy
Description:
Count the number of prime numbers less than a non-negative number, n.
思路:直接看题目中的Hint。关于质数筛选法。
代码:
判断一个数是否为质数:
1 bool isPrime(int n){ 2 if(n<=1){ 3 return false; 4 } 5 bool flag[n+1]={false}; 6 int i; 7 for(i=2;i*i<=n;i){ 8 if(n%i==0){ 9 return false; 10 } 11 } 12 return true; 13 }
形式一:
1 class Solution { 2 public: 3 int countPrimes(int n) { 4 if(n<=1){ 5 return 0; 6 } 7 bool isprime[n]; 8 memset(isprime,true,sizeof(isprime)); 9 int i; 10 for(i=2;i*i<n;i++){ 11 if(!isprime[i]) continue; 12 int j; 13 for(j=i*i;j<n;j+=i){ 14 isprime[j]=false; 15 } 16 } 17 int count=0; 18 for(i=2;i<n;i++){ 19 if(isprime[i]){ 20 count++; 21 } 22 } 23 return count; 24 } 25 };
形式二:
1 class Solution { 2 public: 3 int countPrimes(int n) { 4 if(n<=2){ 5 return 0; 6 } 7 vector<bool> isprime(n,true); 8 int i,count=1,upper=sqrt(n); 9 for(i=3;i<n;i+=2){ 10 if(!isprime[i]) continue; 11 count++; 12 if(i<=upper){ 13 int j; 14 for(j=i*i;j<n;j+=i){ 15 isprime[j]=false; 16 } 17 } 18 } 19 return count; 20 } 21 };