devela/num/int/fns.rs
1// devela::num::int::fns
2
3#[cfg(all(not(feature = "std"), feature = "_float_f64"))]
4use crate::ExtFloat;
5
6/// The prime number theorem formula.
7///
8/// Returns the approximate count of primes less than the given `n`.
9///
10/// $$ \large \pi(x) \sim \frac{x}{\ln(x)} $$
11///
12/// # Examples
13/// ```
14/// use devela::num::prime_number_theorem as pi;
15///
16/// // Showing the % difference against the real amount, if known.
17/// // Note how precision increases in direct relationship to the power.
18/// assert_eq![pi(u8::MAX.into()), 46]; // 14.81% < 54
19/// assert_eq![pi(u16::MAX.into()), 5909]; // 9.67% < 6542
20///
21/// #[cfg(feature = "std")] // too slow otherwise
22/// {
23/// assert_eq![pi(u32::MAX.into()), 193635251]; // 4.74% < 203280221
24/// assert_eq![pi(u64::MAX.into()), 415828534307635072]; // 2.30% < 425656284035217743
25/// assert_eq![pi(2u128.pow(92)), 77650867634561160386183168]; // 1.59% < 78908656317357166866404346
26/// assert_eq![pi(u128::MAX.into()), 3835341275459348115779911081237938176]; // ?% < ?
27/// }
28/// ```
29/// # Links
30/// - <https://mathworld.wolfram.com/PrimeNumberTheorem.html>
31/// - <https://en.wikipedia.org/wiki/Prime_number_theorem>
32/// - The exact prime count till $2^{92}$ is available in <https://oeis.org/A007053>.
33//
34// IMPROVE: use big int and big float.
35#[must_use]
36#[cfg(any(feature = "std", feature = "_float_f64"))]
37#[cfg_attr(feature = "nightly_doc", doc(cfg(any(feature = "std", feature = "_float_f64"))))]
38pub fn prime_number_theorem(n: u128) -> u128 {
39 #[allow(clippy::cast_precision_loss)]
40 let float_n = n as f64;
41 let ln_n = float_n.ln();
42 #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
43 return (float_n / ln_n).round() as u128;
44}