Topic
- Hash Table
- Math
Description
https://leetcode.com/problems/count-primes/
Count the number of prime numbers less than a non-negative number, n.
Example 1:
Input: n = 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Example 2:
Input: n = 0
Output: 0
Example 3:
Input: n = 1
Output: 0
Constraints:
- 0 <= n <= 5 * 10⁶
Analysis
埃拉托色尼筛选法(the Sieve of Eratosthenes)简称埃氏筛法,是古希腊数学家埃拉托色尼(Eratosthenes 274B.C.~194B.C.)提出的一种筛选法。 是针对自然数列中的自然数而实施的,用于求一定范围内的质数,它的容斥原理之完备性条件是p=H~。埃拉托色尼筛选法_百度百科
Submission
public class CountPrimes {
public int countPrimes(int n) {
boolean[] notPrime = new boolean[n];
int count = 0;
for (int i = 2; i < n; i++) {
if (!notPrime[i]) {
count++;
for (int j = i; i * j < n; j++) {
notPrime[i * j] = true;
}
}
}
return count;
}
}
Test
import static org.junit.Assert.*;
import org.junit.Test;
public class CountPrimesTest {
@Test
public void test() {
CountPrimes obj = new CountPrimes();
assertEquals(4, obj.countPrimes(10));
assertEquals(0, obj.countPrimes(0));
assertEquals(0, obj.countPrimes(1));
}
}
来源:oschina
链接:https://my.oschina.net/jallenkwong/blog/4845699