0%

LeetCode-204

题目

Snipaste_2020-12-03_09-45-52.png

结果

Snipaste_2020-12-03_09-45-58.png

代码

直接挨个儿判断是不是质数,就算是开了方的那种也会超时。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int countPrimes(int n) {
int ans = 0;
for (int i = 2; i < n; ++i) {
ans += isPrime(i) ? 1 : 0;
}
return ans;
}

public boolean isPrime(int x) {
for (int i = 2; i * i <= x; ++i) {
if (x % i == 0) {
return false;
}
}
return true;
}
}

利用数组:

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
class Solution {
public int countPrimes(int n) {
if (n < 2) {
return 0;
}
boolean[] prime = new boolean[n];
prime[0] = true;
prime[1] = true;
for (int i = 2; i < Math.sqrt(n); i++) {
if (!prime[i]) {
for (int j = 2; i * j < n; j++) {
prime[i * j] = true;
}
}
}

int count = 0;
for (boolean flag : prime) {
if (!flag) {
count++;
}
}
return count;
}
}

复杂度

不好算