1 static int wing=[]()
 2 {
 3     std::ios::sync_with_stdio(false);
 4     cin.tie(NULL);
 5     return 0;
 6 }();
 7 
 8 class Solution 
 9 {
10 public:
11     int countPrimes(int n) 
12     {
13         if(n<3)
14             return 0;
15         int sqr=sqrt(n);
16         vector<bool> flag(n,false);
17         int count=n/2;
18         for(int i=3;i<=sqr;i+=2)
19         {
20             if(flag[i])
21                 continue;
22             for(int j=i*i;j<n;j+=(i<<1))
23             {
24                 if(!flag[j])
25                     count--;
26                 flag[j]=true;
27             }
28         }
29         return count;
30     }
31 };

这里用了厄拉多塞筛选法:

其实,当你要画圈的素数的平方大于 n 时,那么后面没有划去的数都是素数,就不用继续判了。如下图:

上面代码中的算法还对这个筛选法进行了细微的优化,比如只判定奇数,计数器从n/2开始减少。

posted on 2018-05-23 10:01  高数考了59  阅读(148)  评论(0)    收藏  举报