Skip to content

Commit 91f3155

Browse files
committed
solve 204.count-primes
1 parent 510fb43 commit 91f3155

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

vscode/204.count-primes.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
* @lc app=leetcode id=204 lang=java
3+
*
4+
* [204] Count Primes
5+
*
6+
* https://leetcode.com/problems/count-primes/description/
7+
*
8+
* algorithms
9+
* Easy (28.26%)
10+
* Total Accepted: 227K
11+
* Total Submissions: 791.5K
12+
* Testcase Example: '10'
13+
*
14+
* Count the number of prime numbers less than a non-negative number, n.
15+
*
16+
* Example:
17+
*
18+
*
19+
* Input: 10
20+
* Output: 4
21+
* Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
22+
*
23+
*
24+
*/
25+
class Solution {
26+
public int countPrimes(int n) {
27+
boolean[] primes = new boolean[n];
28+
Arrays.fill(primes, true);
29+
30+
for (int i = 2; i <= Math.sqrt(n-1); i++) {
31+
if (primes[i]) {
32+
for (int j = i*i; j < n; j += i) {
33+
primes[j] = false;
34+
}
35+
}
36+
}
37+
38+
int count = 0;
39+
for (int i = 2; i < n; i++) {
40+
if (primes[i]) {
41+
count++;
42+
}
43+
}
44+
45+
return count;
46+
}
47+
}
48+

0 commit comments

Comments
 (0)