Skip to content

Commit 2fa88a3

Browse files
committed
add _204_ 统计素数
1 parent fb185a9 commit 2fa88a3

2 files changed

Lines changed: 91 additions & 0 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ Utils/.DS_Store
99
Utils/jdk8新特性/lambda/lambda_demo/.idea/$CACHE_FILE$
1010
*.class
1111
Algorithm/LeetCode/leetcode/.idea/workspace.xml
12+
Algorithm/LeetCode/leetcode/.idea/workspace.xml
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
package easy;
2+
3+
/**
4+
* @Author: leosanqing
5+
* @Date: 2020/4/15 上午11:19
6+
* @Package: easy
7+
* @Description: 统计素数个数
8+
* @Version: 1.0
9+
* <p>
10+
* <p>
11+
* 204. Count Primes
12+
* Des:
13+
* Count the number of prime numbers less than a non-negative number, n.
14+
* <p>
15+
* Example:
16+
* <p>
17+
* Input: 10
18+
* Output: 4
19+
* Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
20+
*/
21+
public class _204_countPrimes {
22+
public static void main(String[] args) {
23+
// System.out.println(new _204_countPrimes().countPrimes(499979));
24+
int num = 49997;
25+
System.out.println((new _204_countPrimes().countPrimes(num)) == new _204_countPrimes().countPrimesFast(num));
26+
// System.out.println(new _204_countPrimes().countPrimesFast(499979));
27+
}
28+
//
29+
30+
/**
31+
* 效率太低 O(n²)
32+
*
33+
* @param n
34+
* @return
35+
*/
36+
public int countPrimes(int n) {
37+
if (n <= 2) {
38+
return 0;
39+
}
40+
41+
if (n == 3) {
42+
return 1;
43+
}
44+
45+
boolean flag = false;
46+
int num = 2;
47+
for (int i = 3; i < n; i++) {
48+
flag = false;
49+
50+
for (int j = 2; j <= i / 2; j++) {
51+
if (i % j == 0) {
52+
break;
53+
}
54+
if (j == i / 2) {
55+
flag = true;
56+
break;
57+
}
58+
}
59+
60+
if (flag) {
61+
num++;
62+
}
63+
64+
}
65+
return num;
66+
}
67+
68+
/**
69+
* O(n·log(log(n)))
70+
* 我们设置一个 bool 型的 数组,长度为 我们要输入的长度
71+
* 从
72+
*
73+
* @param n
74+
* @return
75+
*/
76+
public int countPrimesFast(int n) {
77+
boolean[] notPrime = new boolean[n];
78+
int count = 0;
79+
for (int i = 2; i < n; i++) {
80+
if (!notPrime[i]) {
81+
count++;
82+
for (int j = 2; i * j < n; j++) {
83+
notPrime[i * j] = true;
84+
}
85+
}
86+
}
87+
88+
return count;
89+
}
90+
}

0 commit comments

Comments
 (0)