Skip to content

Commit 7770aef

Browse files
committed
solve problem Count Primes
1 parent c337cc6 commit 7770aef

File tree

5 files changed

+75
-0
lines changed

5 files changed

+75
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,7 @@ All solutions will be accepted!
190190
|532|[K Diff Pairs In An Array](https://leetcode-cn.com/problems/k-diff-pairs-in-an-array/description/)|[java/py/js](./algorithms/KDiffPairsInAnArray)|Easy|
191191
|633|[Sum Of Square Numbers](https://leetcode-cn.com/problems/sum-of-square-numbers/description/)|[java/py/js](./algorithms/SumOfSquareNumbers)|Easy|
192192
|605|[Can Place Flowers](https://leetcode-cn.com/problems/can-place-flowers/description/)|[java/py/js](./algorithms/CanPlaceFlowers)|Easy|
193+
|204|[Count Primes](https://leetcode-cn.com/problems/count-primes/description/)|[java/py/js](./algorithms/CountPrimes)|Easy|
193194

194195
# Database
195196
|#|Title|Solution|Difficulty|

Diff for: algorithms/CountPrimes/README.md

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Count Primes
2+
This problem is easy to solve by Sieve of Eratosthenes
3+
The js solution will not accept on leetcode-cn but ok on leetcode

Diff for: algorithms/CountPrimes/Solution.java

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
public int countPrimes(int n) {
3+
boolean[] primes = new boolean[Math.max(n, 2)];
4+
Arrays.fill(primes, true);
5+
primes[0] = primes[1] = false;
6+
int count = 0;
7+
8+
for (int i = 2; i < n; i++) {
9+
if (primes[i]) {
10+
for (int j = i * 2; j < n; j += i) {
11+
primes[j] = false;
12+
}
13+
}
14+
}
15+
16+
for (int i = 2; i < n; i++) {
17+
if (primes[i]) {
18+
count++;
19+
}
20+
}
21+
22+
return count;
23+
}
24+
}

Diff for: algorithms/CountPrimes/solution.js

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @param {number} n
3+
* @return {number}
4+
*/
5+
var countPrimes = function(n) {
6+
let primes = new Array(Math.max(n, 2)),
7+
count = 0
8+
9+
primes.fill(true)
10+
primes[0] = primes[1] = false
11+
12+
for (let i = 2; i < n; i++) {
13+
if (primes[i]) {
14+
for (let j = i * 2; j < n; j += i) {
15+
primes[j] = false
16+
}
17+
}
18+
}
19+
20+
for (let i = 2; i < n; i++) {
21+
if (primes[i]) {
22+
count++
23+
}
24+
}
25+
return count
26+
};

Diff for: algorithms/CountPrimes/solution.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution(object):
2+
def countPrimes(self, n):
3+
"""
4+
:type n: int
5+
:rtype: int
6+
"""
7+
prime_list = [True] * max(n, 2)
8+
prime_list[0] = prime_list[1] = False
9+
10+
for i in range(2, n):
11+
if prime_list[i]:
12+
j = i * 2
13+
while j < n:
14+
prime_list[j] = False
15+
j += i
16+
17+
count = 0
18+
for i in range(2, n):
19+
if prime_list[i]:
20+
count += 1
21+
return count

0 commit comments

Comments
 (0)