顿搜
飞过闲红千叶,夕岸在哪
类目归类
Count the number of prime numbers less than a non-negative number, n.
Input 5
Output 2
public int countPrimes(int n) {
if (n < 3) {
return 0;
}
boolean[] primes = new boolean[n];
int sqrt = (int) Math.ceil(Math.sqrt(n - 1));
for (int i = 2; i <= sqrt; i++) {
if (primes[i]) {
continue;
}
for (int j = i + i; j < n; j += i) {
primes[j] = true;
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (!primes[i]) {
count++;
}
}
return count;
}public class LeetCode0204 {
public int countPrimes(int n) {
if (n < 3) {
return 0;
}
boolean[] primes = new boolean[n];
int sqrt = (int) Math.ceil(Math.sqrt(n - 1));
for (int i = 2; i <= sqrt; i++) {
if (primes[i]) {
continue;
}
for (int j = i + i; j < n; j += i) {
primes[j] = true;
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (!primes[i]) {
count++;
}
}
return count;
}
public static void main(String[] args) {
LeetCode0204 leetcode = new LeetCode0204();
System.out.println(leetcode.countPrimes(5));
}
}