题目:leetcode
Count Primes
Description:
Count the number of prime numbers less than a non-negative number, n
分析:
求出比n小的素数的个数,这个问题可以用排除法做,参考http://www.cnblogs.com/grandyang/p/4462810.html
int countPrimes(int n) { if(n<=2) return 0; int res=0; int size=sqrt(n); vector<char> b(n+1,true); for(int i=2;i<=size;++i) { if(b[i]==false) continue; for(int j=2*i,k=3;j<n;j=k*i,++k) { b[j]=false; } } for(int i=2;i<n;++i) { if(b[i]==true) ++res; } return res; }
原文:http://blog.csdn.net/bupt8846/article/details/45340787