Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
求在n范围内,素数的个数.
1.直接暴力循环法,思路清晰,但是复杂度高.不可以AC
class Solution { public: bool isprime(int n) { for(int i=2;i<n;i++) if(n%i==0) return false; return true; } int countPrimes(int n) { int m=0; for(int i=2;i<n;i++) { if(isprime(i)) m++; } return m; } };2.https://www.cnblogs.com/grandyang/p/4462810.html 埃拉托斯特尼筛法 从2开始遍历到根号n,先找到第一个质数2,然后将其所有的倍数全部标记出来,然后到下一个质数3,标记其所有倍数,一次类推,直到根号n,此时数组中未被标记的数字就是质数。
class Solution { public: int countPrimes(int n) { vector<bool> prime(n,true); int res = 0; for(int i=2;i<n;i++) { if(prime[i]) ++res; for(int j=2;i*j<n;j++) { prime[i*j]=false; } } return res; } };