const_primes/
count.rs

1use crate::sieve;
2
3/// Returns an array of size `N` where the value at a given index is how many primes are less than or equal to the index.
4///
5/// Sieves primes with [`sieve`](crate::sieve()) and then counts them.
6///
7/// # Example
8///
9/// Basic usage
10///
11/// ```
12/// # use const_primes::prime_pi;
13/// const COUNTS: [usize; 10] = prime_pi();
14/// assert_eq!(COUNTS, [0, 0, 1, 2, 2, 3, 3, 4, 4, 4]);
15/// ```
16#[must_use = "the function only returns a new value"]
17pub const fn prime_pi<const N: usize>() -> [usize; N] {
18    let mut counts = [0; N];
19    if N <= 2 {
20        return counts;
21    }
22    counts[2] = 1;
23    let prime_status: [bool; N] = sieve();
24    let mut count = 1;
25    let mut i = 3;
26    while i < N {
27        if prime_status[i] {
28            count += 1;
29        }
30        counts[i] = count;
31        if i + 1 < N {
32            counts[i + 1] = count;
33        }
34        i += 2;
35    }
36    counts
37}