package leetcode.editor.cn;
//统计所有小于非负整数 n 的质数的数量。
//
// 示例:
//
// 输入: 10
//输出: 4
//解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
//
// Related Topics 哈希表 数学
//Java:计数质数
public class P204计数质数{
public static void main(String[] args) {
Solution solution = new P204计数质数().new Solution();
// TO TEST
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int countPrimes(int n) {
int[] nums = new int[n];
for (int i = 2; i < n; i++) {
if (nums[i] == 1) {
continue;
}
int badNum = 2;
while (badNum * i < n) {
nums[badNum * i ] = 1;
badNum++;
}
}
int ans = 0;
for (int i = 2; i < n; i++) {
if (nums[i] == 0) {
ans++;
}
}
return ans;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
LeetCode204【Null】:计数质数
猜你喜欢
转载自blog.csdn.net/baidu_34209307/article/details/105108034
今日推荐
周排行