LeetCode 204 - Count Primes - 题解/Solution

https://leetcode.com/problems/count-primes/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Count the number of prime numbers less than a non-negative number, n
*
* @author dongyuxi
*
*/
public class Solution {
public int countPrimes(int n) {
if (n <= 2) {
return 0;
}
boolean[] prime = new boolean[n];
for (int i = 2; i * i < n; i++) {
if (!prime[i]) {
for (int j = i; i * j < n; j++) {
prime[i * j] = true;
}
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (!prime[i]) {
count++;
}
}
return count;
}
}


支付宝 微信
文章目录