Leetcode 204 Count Primes
//比n小的质数有几个
//(质数筛选定理)n不能够被小于等于根号n的任何质数整除,则n是一个质数
#include <math.h>
class Solution {
public:
int countPrimes(int n) {
int count = 1;
if (n <= 2)
return 0;
for (int i = 3; i < n; i += 2){//偶数都不是质数
//float temp = static_cast<float>(i);
//int mid = static_cast<int>(sqrt(temp));
int mid = sqrt((float)i);
int j = 0;
for (j = 3; j <= mid; j += 2){
if (i % j == 0)
break;
}
if (j > mid)
count++;
}
return count;
}
};//很慢的样子……