题目统计所有小于非负整数 n 的质数的数量。 示例: 123输入: 10输出: 4解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 Related Topics 哈希表 数学 解答123456789101112131415161718192021222324252627282930313233//统计所有小于非负整数 n 的质数的数量。 //// 示例: //// 输入: 10//输出: 4//解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。// // Related Topics 哈希表 数学//leetcode submit region begin(Prohibit modification and deletion)class Solution { public int countPrimes(int n) { boolean[] isPrim = new boolean[n]; // 将数组都初始化为 true Arrays.fill(isPrim, true); for (int i = 2; i < n; i++) if (isPrim[i]) // i 的倍数不可能是素数了 for (int j = 2 * i; j < n; j += i) isPrim[j] = false; int count = 0; for (int i = 2; i < n; i++) if (isPrim[i]) count++; return count; }}//leetcode submit region end(Prohibit modification and deletion)文章作者: 无知的小狼文章链接: https://bytedance.press/2020/04/28/20200401/day4_204_%E8%AE%A1%E7%AE%97%E8%B4%A8%E6%95%B0/版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 无知的小狼!刷题上一篇day5_242_有效的字母异位词下一篇day3四数之和 相关推荐 2020-04-25day1两数之和 2020-04-27day3四数之和 2020-04-26day2三数之和 2020-04-30day6_28_实现 [strStr()](https://baike.baidu.com/item/strstr/811469) 函数 2020-04-29day5_242_有效的字母异位词 2020-05-05day11_234_回文链表 评论