LeetCode | Count Primes

来源:互联网 发布:怎么做好淘宝网店 编辑:程序博客网 时间:2024/06/12 01:02

Count Primes

 Total Accepted: 10553 Total Submissions: 56521My Submissions

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;       }    }};


0 0
原创粉丝点击