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.
思路:求小于n值的质数个数,主要考查求质数的优化算法,相对简单。
class Solution { public: int countPrimes(int n) { if(n<=2) return 0; else { int cnt=0; int *arr=new int[n+10]; for(int i=0;i<=n+9;i++) arr[i]=0; for(int i=2;i<=n-1;i++) { if(!arr[i]){ cnt++; } for(int j=i*2;j<=n-1;j+=i) { arr[j]=1; } } return cnt; } } };
版权声明:本文为博主原创文章,未经博主允许不得转载。