From 444a999efe8299238dbde6d6a4e48a9526376f3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=BD=A9=E8=BE=95=E9=BE=99=E5=84=BF?= Date: Tue, 12 Apr 2022 10:59:11 +0800 Subject: [PATCH] =?UTF-8?q?204:=E8=AE=A1=E6=95=B0=E8=B4=A8=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/leetcode/editor/cn/CountPrimes.java | 76 +++++++++++++++++++ .../editor/cn/doc/content/CountPrimes.md | 34 +++++++++ 2 files changed, 110 insertions(+) create mode 100644 src/main/java/leetcode/editor/cn/CountPrimes.java create mode 100644 src/main/java/leetcode/editor/cn/doc/content/CountPrimes.md diff --git a/src/main/java/leetcode/editor/cn/CountPrimes.java b/src/main/java/leetcode/editor/cn/CountPrimes.java new file mode 100644 index 0000000..e16f99d --- /dev/null +++ b/src/main/java/leetcode/editor/cn/CountPrimes.java @@ -0,0 +1,76 @@ +//给定整数 n ,返回 所有小于非负整数 n 的质数的数量 。 +// +// +// +// 示例 1: +// +// +//输入:n = 10 +//输出:4 +//解释:小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。 +// +// +// 示例 2: +// +// +//输入:n = 0 +//输出:0 +// +// +// 示例 3: +// +// +//输入:n = 1 +//输出:0 +// +// +// +// +// 提示: +// +// +// 0 <= n <= 5 * 10⁶ +// +// Related Topics 数组 数学 枚举 数论 👍 869 👎 0 + +package leetcode.editor.cn; + +import java.util.Arrays; + +//204:计数质数 +public class CountPrimes { + public static void main(String[] args) { + Solution solution = new CountPrimes().new Solution(); + // TO TEST + solution.countPrimes(499979); + } + + //leetcode submit region begin(Prohibit modification and deletion) + class Solution { + public int countPrimes(int n) { + if (n <= 2) { + return 0; + } + boolean[] nums = new boolean[n + 1]; + Arrays.fill(nums, true); + nums[0] = false; + nums[1] = false; + int count = 0; + int max = (int) Math.sqrt(n); + for (int i = 2; i < n; i++) { + if (nums[i]) { + count++; + if (i > max) { + continue; + } + for (int j = i; j * i < n; j++) { + nums[j * i] = false; + } + } + } + return count; + } + } +//leetcode submit region end(Prohibit modification and deletion) + +} diff --git a/src/main/java/leetcode/editor/cn/doc/content/CountPrimes.md b/src/main/java/leetcode/editor/cn/doc/content/CountPrimes.md new file mode 100644 index 0000000..a80833d --- /dev/null +++ b/src/main/java/leetcode/editor/cn/doc/content/CountPrimes.md @@ -0,0 +1,34 @@ +

给定整数 n ,返回 所有小于非负整数 n 的质数的数量

+ +

 

+ +

示例 1:

+ +
+输入:n = 10
+输出:4
+解释:小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
+
+ +

示例 2:

+ +
+输入:n = 0
+输出:0
+
+ +

示例 3:

+ +
+输入:n = 1
+输出:0
+
+ +

 

+ +

提示:

+ + +
Related Topics
  • 数组
  • 数学
  • 枚举
  • 数论

  • 👍 869
  • 👎 0
  • \ No newline at end of file