/*
* @lc app=leetcode.cn id=204 lang=typescript
*
* [204] 计数质数
*/
// @lc code=start
function countPrimes(n: number): number {}
// @lc code=end
function countPrimes(n: number): number {
if (n <= 2) return 0
let prime = new Array(n).fill(1)
let res = 0
for (let i = 2; i < n; i++) {
if (!prime[i]) continue
res++
for (let j = i * i; j < n; j += i) {
prime[j] = 0
}
}
return res
}
function countPrimes(n: number): number {
if (n <= 2) return 0
const primes = new Set<number>()
const isPrime = new Array(n).fill(1)
for (let i = 2; i < n; i++) {
if (isPrime[i]) primes.add(i)
for (const prime of primes) {
if (i * prime >= n) break
isPrime[i * prime] = 0
if (!(i % prime)) break
}
}
return primes.size
}
test.each([
{ input: { n: 10 }, output: 4 },
{ input: { n: 0 }, output: 0 },
{ input: { n: 1 }, output: 0 },
{ input: { n: 2 }, output: 0 },
{ input: { n: 3 }, output: 1 },
{ input: { n: 20 }, output: 8 },
])('input: n = $input.n', ({ input: { n }, output }) => {
expect(countPrimes(n)).toBe(output)
})