204. 计数质数
2020-12-03 23:58 woshihuangrulin 阅读(122) 评论(0) 编辑 收藏 举报注意n的最小因数不超过根号(n-1),还有搜查范围是(2,n-1】,如果n小于等于2,返回0,否则个数基础是1(即2),具体代码如下所示:
class Solution { public: int countPrimes(int n) { if (n <= 2) { return 0; } int sum = 1; for (int i = n-1; i > 2; i--) { bool found_target = false; for (int j = 2; j * j <= i; j++) { if (i % j == 0) { found_target = true; break; } } if (found_target == false) { sum++; } } return sum; } };