Debian Codegraph @

debian/rust-vendor/num-prime/src/nt_funcs.rs

raw
1 //! Standalone number theoretic functions
2 //!
3 //! The functions in this module can be called without an instance of [`crate::traits::PrimeBuffer`].
4 //! However, some functions do internally call the implementation on [`PrimeBufferExt`]
5 //! (especially those dependent of integer factorization). For these functions, if you have
6 //! to call them repeatedly, it's recommended to create a [`crate::traits::PrimeBuffer`]
7 //! instance and use its associated methods for better performance.
8 //!
9 //! For number theoretic functions that depends on integer factorization, strongest primality
10 //! check will be used in factorization, since for these functions we prefer correctness
11 //! over speed.
12 //!
13
14 use crate::buffer::{NaiveBuffer, PrimeBufferExt};
15 use crate::factor::{one_line, pollard_rho, squfof, SQUFOF_MULTIPLIERS};
16 use crate::mint::SmallMint;
17 use crate::primality::{PrimalityBase, PrimalityRefBase};
18 use crate::tables::{
19 MOEBIUS_ODD, SMALL_PRIMES, SMALL_PRIMES_NEXT, WHEEL_NEXT, WHEEL_PREV, WHEEL_SIZE,
20 };
21 #[cfg(feature = "big-table")]
22 use crate::tables::{SMALL_PRIMES_INV, ZETA_LOG_TABLE};
23 use crate::traits::{FactorizationConfig, Primality, PrimalityTestConfig, PrimalityUtils};
24 use crate::{BitTest, ExactRoots};
25 use num_integer::Roots;
26 #[cfg(feature = "big-table")]
27 use num_modular::DivExact;
28 use num_modular::{ModularCoreOps, ModularInteger, MontgomeryInt};
29 use num_traits::{CheckedAdd, FromPrimitive, Num, RefNum, ToPrimitive};
30 use rand::random;
31 use std::collections::BTreeMap;
32 use std::convert::TryFrom;
33
34 #[cfg(feature = "big-table")]
35 use crate::tables::{MILLER_RABIN_BASE32, MILLER_RABIN_BASE64};
36
37 /// Fast primality test on a u64 integer. It's based on
38 /// deterministic Miller-rabin tests. If target is larger than 2^64 or more
39 /// controlled primality tests are desired, please use [is_prime()]
40 ///
41 /// # Examples
42 ///
43 /// ```
44 /// use num_prime::nt_funcs::is_prime64;
45 ///
46 /// assert!(is_prime64(2));
47 /// assert!(is_prime64(13));
48 /// assert!(!is_prime64(1));
49 /// assert!(!is_prime64(15));
50 /// assert!(is_prime64(6_469_693_333));
51 /// ```
52 #[cfg(not(feature = "big-table"))]
53 pub fn is_prime64(target: u64) -> bool {
54 // shortcuts
55 if target < 2 {
56 return false;
57 }
58 if target & 1 == 0 {
59 return target == 2;
60 }
61 if let Ok(u) = u8::try_from(target) {
62 // find in the prime list if the target is small enough
63 return SMALL_PRIMES.binary_search(&u).is_ok();
64 } else {
65 // check remainder against the wheel table
66 // this step eliminates any number that is not coprime to WHEEL_SIZE
67 let pos = (target % WHEEL_SIZE as u64) as usize;
68 if pos == 0 || WHEEL_NEXT[pos] < WHEEL_NEXT[pos - 1] {
69 return false;
70 }
71 }
72
73 // Then do a deterministic Miller-rabin test
74 is_prime64_miller(target)
75 }
76
77 /// Very fast primality test on a u64 integer is a prime number. It's based on
78 /// deterministic Miller-rabin tests with hashing. if target is larger than 2^64 or more controlled
79 /// primality tests are desired, please use [`is_prime()`]
80 ///
81 /// # Examples
82 ///
83 /// ```
84 /// use num_prime::nt_funcs::is_prime64;
85 ///
86 /// assert!(is_prime64(2));
87 /// assert!(is_prime64(13));
88 /// assert!(!is_prime64(1));
89 /// assert!(!is_prime64(15));
90 /// assert!(is_prime64(6_469_693_333));
91 /// ```
92 #[cfg(feature = "big-table")]
93 #[must_use]
94 pub fn is_prime64(target: u64) -> bool {
95 // shortcuts
96 if target < 2 {
97 return false;
98 }
99 if target & 1 == 0 {
100 return target == 2;
101 }
102
103 // remove small factors
104 if target < SMALL_PRIMES_NEXT {
105 // find in the prime list if the target is small enough
106 return SMALL_PRIMES.binary_search(&(target as u16)).is_ok();
107 } else {
108 // check remainder against the wheel table
109 // this step eliminates any number that is not coprime to WHEEL_SIZE
110 let pos = (target % u64::from(WHEEL_SIZE)) as usize;
111 if pos == 0 || WHEEL_NEXT[pos] < WHEEL_NEXT[pos - 1] {
112 return false;
113 }
114 }
115
116 // Then do a deterministic Miller-rabin test
117 is_prime64_miller(target)
118 }
119
120 // Primality test for u64 with only miller-rabin tests, used during factorization.
121 // It assumes the target is odd, not too small and cannot be divided small primes
122 #[cfg(not(feature = "big-table"))]
123 fn is_prime64_miller(target: u64) -> bool {
124 // The collection of witnesses are from http://miller-rabin.appspot.com/
125 if let Ok(u) = u32::try_from(target) {
126 const WITNESS32: [u32; 3] = [2, 7, 61];
127 let u = SmallMint::from(u);
128 WITNESS32.iter().all(|&x| u.is_sprp(SmallMint::from(x)))
129 } else {
130 const WITNESS64: [u64; 7] = [2, 325, 9375, 28178, 450775, 9780504, 1795265022];
131 let u = SmallMint::from(target);
132 WITNESS64.iter().all(|&x| u.is_sprp(SmallMint::from(x)))
133 }
134 }
135
136 #[cfg(feature = "big-table")]
137 fn is_prime32_miller(target: u32) -> bool {
138 let h = u64::from(target);
139 let h = ((h >> 16) ^ h).wrapping_mul(0x045d_9f3b);
140 let h = ((h >> 16) ^ h).wrapping_mul(0x045d_9f3b);
141 let h = ((h >> 16) ^ h) & 255;
142 let u = SmallMint::from(target);
143 u.is_sprp(SmallMint::from(u32::from(MILLER_RABIN_BASE32[h as usize])))
144 }
145
146 // Primality test for u64 with only miller-rabin tests, used during factorization.
147 // It assumes the target is odd, not too small and cannot be divided small primes
148 #[cfg(feature = "big-table")]
149 fn is_prime64_miller(target: u64) -> bool {
150 if let Ok(u) = u32::try_from(target) {
151 return is_prime32_miller(u);
152 }
153
154 let u = SmallMint::from(target);
155 if !u.is_sprp(2.into()) {
156 return false;
157 }
158
159 let h = target;
160 let h = ((h >> 32) ^ h).wrapping_mul(0x045d_9f3b_3335_b369);
161 let h = ((h >> 32) ^ h).wrapping_mul(0x0333_5b36_945d_9f3b);
162 let h = ((h >> 32) ^ h) & 16383;
163 let b = MILLER_RABIN_BASE64[h as usize];
164 u.is_sprp((u64::from(b) & 4095).into()) && u.is_sprp((u64::from(b) >> 12).into())
165 }
166
167 /// Fast integer factorization on a u64 target. It's based on a selection of factorization methods.
168 /// if target is larger than 2^128 or more controlled primality tests are desired, please use [`factors()`][crate::buffer::PrimeBufferExt::factors].
169 ///
170 /// The factorization can be quite faster under 2^64 because: 1) faster and deterministic primality check,
171 /// 2) efficient montgomery multiplication implementation of u64
172 ///
173 /// # Examples
174 ///
175 /// ```
176 /// use num_prime::nt_funcs::factorize64;
177 /// use std::collections::BTreeMap;
178 /// use std::iter::FromIterator;
179 ///
180 /// let fac = factorize64(4095);
181 /// assert_eq!(fac, BTreeMap::from_iter([(3, 2), (5, 1), (7, 1), (13, 1)]));
182 ///
183 /// let fac = factorize64(123_456_789);
184 /// assert_eq!(fac, BTreeMap::from_iter([(3, 2), (3607, 1), (3803, 1)]));
185 /// ```
186 #[must_use]
187 pub fn factorize64(target: u64) -> BTreeMap<u64, usize> {
188 // TODO: improve factorization performance
189 // REF: http://flintlib.org/doc/ulong_extras.html#factorisation
190 // https://mathoverflow.net/questions/114018/fastest-way-to-factor-integers-260
191 // https://hal.inria.fr/inria-00188645v3/document
192 // https://github.com/coreutils/coreutils/blob/master/src/factor.c
193 // https://github.com/uutils/coreutils/blob/master/src/uu/factor/src/cli.rs
194 // https://github.com/elmomoilanen/prime-factorization
195 // https://github.com/radii/msieve
196 // https://github.com/zademn/facto-rs
197 // Pari/GP: ifac_crack
198 let mut result = BTreeMap::new();
199
200 // quick check on factors of 2
201 let f2 = target.trailing_zeros();
202 if f2 == 0 {
203 if is_prime64(target) {
204 result.insert(target, 1);
205 return result;
206 }
207 } else {
208 result.insert(2, f2 as usize);
209 }
210
211 // trial division using primes in the table
212 let tsqrt = target.sqrt() + 1;
213
214 let mut residual = target >> f2;
215 let mut factored = false;
216
217 #[cfg(not(feature = "big-table"))]
218 for p in SMALL_PRIMES.iter().skip(1).map(|&v| v as u64) {
219 if p > tsqrt {
220 factored = true;
221 break;
222 }
223
224 while residual % p == 0 {
225 residual = residual / p;
226 *result.entry(p).or_insert(0) += 1;
227 }
228 if residual == 1 {
229 factored = true;
230 break;
231 }
232 }
233
234 #[cfg(feature = "big-table")]
235 // divisibility check with pre-computed tables, see comments on SMALL_PRIMES_INV for reference
236 for (p, &pinv) in SMALL_PRIMES
237 .iter()
238 .map(|&p| u64::from(p))
239 .zip(SMALL_PRIMES_INV.iter())
240 .skip(1)
241 {
242 // only need to test primes up to sqrt(target)
243 if p > tsqrt {
244 factored = true;
245 break;
246 }
247
248 let mut exp: usize = 0;
249 while let Some(q) = DivExact::div_exact(residual, p, &pinv) {
250 exp += 1;
251 residual = q;
252 }
253 if exp > 0 {
254 result.insert(p, exp);
255 }
256
257 if residual == 1 {
258 factored = true;
259 break;
260 }
261 }
262
263 if factored {
264 if residual != 1 {
265 result.insert(residual, 1);
266 }
267 return result;
268 }
269
270 // then try advanced methods to find a divisor util fully factored
271 for (p, exp) in factorize64_advanced(&[(residual, 1usize)]) {
272 *result.entry(p).or_insert(0) += exp;
273 }
274 result
275 }
276
277 // This function factorize all cofactors after some trivial division steps
278 pub(crate) fn factorize64_advanced(cofactors: &[(u64, usize)]) -> Vec<(u64, usize)> {
279 let mut todo: Vec<_> = cofactors.to_vec();
280 let mut factored: Vec<(u64, usize)> = Vec::new(); // prime factor, exponent
281
282 while let Some((target, exp)) = todo.pop() {
283 if is_prime64_miller(target) {
284 factored.push((target, exp));
285 continue;
286 }
287
288 // check perfect powers before other methods, this is required for SQUFOF
289 // it suffices to check square and cubic if big-table is enabled, since fifth power of
290 // the smallest prime that haven't been checked is 8167^5 > 2^64
291 if let Some(d) = target.sqrt_exact() {
292 todo.push((d, exp * 2));
293 continue;
294 }
295 if let Some(d) = target.cbrt_exact() {
296 todo.push((d, exp * 3));
297 continue;
298 }
299
300 // try to find a divisor
301 let mut i = 0usize;
302 let mut max_iter_ratio = 1; // increase max_iter after factorization round
303 let divisor = loop {
304 // try various factorization method iteratively
305 const NMETHODS: usize = 3;
306 match i % NMETHODS {
307 0 => {
308 // Pollard's rho (quick check)
309 let start = MontgomeryInt::new(random::<u64>(), &target);
310 let offset = start.convert(random::<u64>());
311 let max_iter = max_iter_ratio << (target.bits() / 6); // unoptimized heuristic
312 if let (Some(p), _) = pollard_rho(
313 &SmallMint::from(target),
314 start.into(),
315 offset.into(),
316 max_iter,
317 ) {
318 break p.value();
319 }
320 }
321 1 => {
322 // Hart's one-line (quick check)
323 let mul_target = target.checked_mul(480).unwrap_or(target);
324 let max_iter = max_iter_ratio << (mul_target.bits() / 6); // unoptimized heuristic
325 if let (Some(p), _) = one_line(&target, mul_target, max_iter) {
326 break p;
327 }
328 }
329 2 => {
330 // Shanks's squfof (main power)
331 let mut d = None;
332 for &k in &SQUFOF_MULTIPLIERS {
333 if let Some(mul_target) = target.checked_mul(u64::from(k)) {
334 let max_iter = max_iter_ratio * 2 * mul_target.sqrt().sqrt() as usize;
335 if let (Some(p), _) = squfof(&target, mul_target, max_iter) {
336 d = Some(p);
337 break;
338 }
339 }
340 }
341 if let Some(p) = d {
342 break p;
343 }
344 }
345 _ => unreachable!(),
346 }
347 i += 1;
348
349 // increase max iterations after trying all methods
350 if i % NMETHODS == 0 {
351 max_iter_ratio *= 2;
352 }
353 };
354 todo.push((divisor, exp));
355 todo.push((target / divisor, exp));
356 }
357 factored
358 }
359
360 /// Fast integer factorization on a u128 target. It's based on a selection of factorization methods.
361 /// if target is larger than 2^128 or more controlled primality tests are desired, please use [`factors()`][crate::buffer::PrimeBufferExt::factors].
362 ///
363 /// # Examples
364 ///
365 /// ```
366 /// use num_prime::nt_funcs::factorize128;
367 /// use std::collections::BTreeMap;
368 /// use std::iter::FromIterator;
369 ///
370 /// let fac = factorize128(4095);
371 /// assert_eq!(fac, BTreeMap::from_iter([(3, 2), (5, 1), (7, 1), (13, 1)]));
372 ///
373 /// let fac = factorize128(8167u128.pow(3));
374 /// assert_eq!(fac, BTreeMap::from_iter([(8167, 3)]));
375 /// ```
376 #[must_use]
377 pub fn factorize128(target: u128) -> BTreeMap<u128, usize> {
378 // shortcut for u64
379 if target < (1u128 << 64) {
380 return factorize64(target as u64)
381 .into_iter()
382 .map(|(k, v)| (u128::from(k), v))
383 .collect();
384 }
385
386 let mut result = BTreeMap::new();
387
388 // quick check on factors of 2
389 let f2 = target.trailing_zeros();
390 if f2 != 0 {
391 result.insert(2, f2 as usize);
392 }
393 let mut residual = target >> f2;
394
395 // trial division using primes in the table
396 // note that p^2 is never larger than target (at least 64 bits), so we don't need to shortcut trial division
397 #[cfg(not(feature = "big-table"))]
398 for p in SMALL_PRIMES.iter().skip(1).map(|&v| v as u128) {
399 while residual % p == 0 {
400 residual = residual / p;
401 *result.entry(p).or_insert(0) += 1;
402 }
403 if residual == 1 {
404 return result;
405 }
406 }
407
408 #[cfg(feature = "big-table")]
409 // divisibility check with pre-computed tables, see comments on SMALL_PRIMES_INV for reference
410 for (p, &pinv) in SMALL_PRIMES
411 .iter()
412 .map(|&p| u64::from(p))
413 .zip(SMALL_PRIMES_INV.iter())
414 .skip(1)
415 {
416 let mut exp: usize = 0;
417 while let Some(q) = DivExact::div_exact(residual, p, &pinv) {
418 exp += 1;
419 residual = q;
420 }
421 if exp > 0 {
422 result.insert(u128::from(p), exp);
423 }
424
425 if residual == 1 {
426 return result;
427 }
428 }
429
430 // then try advanced methods to find a divisor util fully factored
431 for (p, exp) in factorize128_advanced(&[(residual, 1usize)]) {
432 *result.entry(p).or_insert(0) += exp;
433 }
434 result
435 }
436
437 pub(crate) fn factorize128_advanced(cofactors: &[(u128, usize)]) -> Vec<(u128, usize)> {
438 let (mut todo128, mut todo64) = (Vec::new(), Vec::new()); // cofactors to be processed
439 let mut factored: Vec<(u128, usize)> = Vec::new(); // prime factor, exponent
440 for &(co, e) in cofactors {
441 if let Ok(co64) = u64::try_from(co) {
442 todo64.push((co64, e));
443 } else {
444 todo128.push((co, e));
445 };
446 }
447
448 while let Some((target, exp)) = todo128.pop() {
449 if is_prime(&SmallMint::from(target), Some(PrimalityTestConfig::bpsw())).probably() {
450 factored.push((target, exp));
451 continue;
452 }
453
454 // check perfect powers before other methods
455 // it suffices to check 2, 3, 5, 7 power if big-table is enabled, since tenth power of
456 // the smallest prime that haven't been checked is 8167^10 > 2^128
457 if let Some(d) = target.sqrt_exact() {
458 if let Ok(d64) = u64::try_from(d) {
459 todo64.push((d64, exp * 2));
460 } else {
461 todo128.push((d, exp * 2));
462 }
463 continue;
464 }
465 if let Some(d) = target.cbrt_exact() {
466 if let Ok(d64) = u64::try_from(d) {
467 todo64.push((d64, exp * 3));
468 } else {
469 todo128.push((d, exp * 3));
470 }
471 continue;
472 }
473 // TODO: check 5-th, 7-th power
474
475 // try to find a divisor
476 let mut i = 0usize;
477 let mut max_iter_ratio = 1;
478
479 let divisor = loop {
480 // try various factorization method iteratively, sort by time per iteration
481 const NMETHODS: usize = 3;
482 match i % NMETHODS {
483 0 => {
484 // Pollard's rho
485 let start = MontgomeryInt::new(random::<u128>(), &target);
486 let offset = start.convert(random::<u128>());
487 let max_iter = max_iter_ratio << (target.bits() / 6); // unoptimized heuristic
488 if let (Some(p), _) = pollard_rho(
489 &SmallMint::from(target),
490 start.into(),
491 offset.into(),
492 max_iter,
493 ) {
494 break p.value();
495 }
496 }
497 1 => {
498 // Hart's one-line
499 let mul_target = target.checked_mul(480).unwrap_or(target);
500 let max_iter = max_iter_ratio << (mul_target.bits() / 6); // unoptimized heuristic
501 if let (Some(p), _) = one_line(&target, mul_target, max_iter) {
502 break p;
503 }
504 }
505 2 => {
506 // Shanks's squfof, try all mutipliers
507 let mut d = None;
508 for &k in &SQUFOF_MULTIPLIERS {
509 if let Some(mul_target) = target.checked_mul(u128::from(k)) {
510 let max_iter = max_iter_ratio * 2 * mul_target.sqrt().sqrt() as usize;
511 if let (Some(p), _) = squfof(&target, mul_target, max_iter) {
512 d = Some(p);
513 break;
514 }
515 }
516 }
517 if let Some(p) = d {
518 break p;
519 }
520 }
521 _ => unreachable!(),
522 }
523 i += 1;
524
525 // increase max iterations after trying all methods
526 if i % NMETHODS == 0 {
527 max_iter_ratio *= 2;
528 }
529 };
530
531 if let Ok(d64) = u64::try_from(divisor) {
532 todo64.push((d64, exp));
533 } else {
534 todo128.push((divisor, exp));
535 }
536 let co = target / divisor;
537 if let Ok(d64) = u64::try_from(co) {
538 todo64.push((d64, exp));
539 } else {
540 todo128.push((co, exp));
541 }
542 }
543
544 // forward 64 bit cofactors
545 factored.extend(
546 factorize64_advanced(&todo64)
547 .into_iter()
548 .map(|(p, exp)| (u128::from(p), exp)),
549 );
550 factored
551 }
552
553 /// Primality test
554 ///
555 /// This function re-exports [`PrimeBufferExt::is_prime()`][crate::buffer::PrimeBufferExt::is_prime()] with a new [`NaiveBuffer`] instance
556 ///
557 /// # Examples
558 ///
559 /// ```
560 /// use num_prime::nt_funcs::is_prime;
561 ///
562 /// assert!(is_prime(&2u64, None).probably());
563 /// assert!(is_prime(&13u64, None).probably());
564 /// assert!(!is_prime(&15u64, None).probably());
565 /// ```
566 pub fn is_prime<T: PrimalityBase>(target: &T, config: Option<PrimalityTestConfig>) -> Primality
567 where
568 for<'r> &'r T: PrimalityRefBase<T>,
569 {
570 NaiveBuffer::new().is_prime(target, config)
571 }
572
573 /// Faillible factorization
574 ///
575 /// This function re-exports [`PrimeBufferExt::factors()`][crate::buffer::PrimeBufferExt::factors()] with a new [`NaiveBuffer`] instance
576 ///
577 /// # Examples
578 ///
579 /// ```
580 /// use num_prime::nt_funcs::factors;
581 ///
582 /// let (fac, unfactored) = factors(60u64, None);
583 /// assert_eq!(fac[&2], 2);
584 /// assert_eq!(fac[&3], 1);
585 /// assert_eq!(fac[&5], 1);
586 /// assert!(unfactored.is_none());
587 /// ```
588 pub fn factors<T: PrimalityBase>(
589 target: T,
590 config: Option<FactorizationConfig>,
591 ) -> (BTreeMap<T, usize>, Option<Vec<T>>)
592 where
593 for<'r> &'r T: PrimalityRefBase<T>,
594 {
595 NaiveBuffer::new().factors(target, config)
596 }
597
598 /// Infaillible factorization
599 ///
600 /// This function re-exports [`PrimeBufferExt::factorize()`][crate::buffer::PrimeBufferExt::factorize()] with a new [`NaiveBuffer`] instance
601 ///
602 /// # Examples
603 ///
604 /// ```
605 /// use num_prime::nt_funcs::factorize;
606 ///
607 /// let fac = factorize(60u64);
608 /// assert_eq!(fac[&2], 2);
609 /// assert_eq!(fac[&3], 1);
610 /// assert_eq!(fac[&5], 1);
611 /// ```
612 pub fn factorize<T: PrimalityBase>(target: T) -> BTreeMap<T, usize>
613 where
614 for<'r> &'r T: PrimalityRefBase<T>,
615 {
616 NaiveBuffer::new().factorize(target)
617 }
618
619 /// Get a list of primes under a limit
620 ///
621 /// This function re-exports [`NaiveBuffer::primes()`] and collect result as a vector.
622 ///
623 /// # Examples
624 ///
625 /// ```
626 /// use num_prime::nt_funcs::primes;
627 ///
628 /// assert_eq!(primes(20), vec![2, 3, 5, 7, 11, 13, 17, 19]);
629 /// assert_eq!(primes(2), vec![2]);
630 /// assert!(primes(1).is_empty());
631 /// ```
632 #[must_use]
633 pub fn primes(limit: u64) -> Vec<u64> {
634 NaiveBuffer::new().into_primes(limit).collect()
635 }
636
637 /// Get the first n primes
638 ///
639 /// This function re-exports [`NaiveBuffer::nprimes()`] and collect result as a vector.
640 ///
641 /// # Examples
642 ///
643 /// ```
644 /// use num_prime::nt_funcs::nprimes;
645 ///
646 /// assert_eq!(nprimes(5), vec![2, 3, 5, 7, 11]);
647 /// assert!(nprimes(0).is_empty());
648 /// ```
649 #[must_use]
650 pub fn nprimes(count: usize) -> Vec<u64> {
651 NaiveBuffer::new().into_nprimes(count).collect()
652 }
653
654 /// Calculate and return the prime π function
655 ///
656 /// This function re-exports [`NaiveBuffer::prime_pi()`]
657 ///
658 /// # Examples
659 ///
660 /// ```
661 /// use num_prime::nt_funcs::prime_pi;
662 ///
663 /// assert_eq!(prime_pi(10), 4); // primes: 2, 3, 5, 7
664 /// assert_eq!(prime_pi(100), 25);
665 /// ```
666 #[must_use]
667 pub fn prime_pi(limit: u64) -> u64 {
668 NaiveBuffer::new().prime_pi(limit)
669 }
670
671 /// Get the n-th prime (n counts from 1).
672 ///
673 /// This function re-exports [`NaiveBuffer::nth_prime()`]
674 ///
675 /// # Examples
676 ///
677 /// ```
678 /// use num_prime::nt_funcs::nth_prime;
679 ///
680 /// assert_eq!(nth_prime(1), 2);
681 /// assert_eq!(nth_prime(5), 11);
682 /// assert_eq!(nth_prime(25), 97);
683 /// ```
684 #[must_use]
685 pub fn nth_prime(n: u64) -> u64 {
686 NaiveBuffer::new().nth_prime(n)
687 }
688
689 /// Calculate the primorial function
690 ///
691 /// Returns the product of the first `n` primes.
692 ///
693 /// # Examples
694 ///
695 /// ```
696 /// use num_prime::nt_funcs::primorial;
697 ///
698 /// assert_eq!(primorial::<u64>(1), 2); // 2
699 /// assert_eq!(primorial::<u64>(3), 30); // 2 * 3 * 5
700 /// assert_eq!(primorial::<u64>(4), 210); // 2 * 3 * 5 * 7
701 /// ```
702 #[must_use]
703 pub fn primorial<T: PrimalityBase + std::iter::Product>(n: usize) -> T {
704 NaiveBuffer::new()
705 .into_nprimes(n)
706 .map(|p| T::from_u64(p).unwrap())
707 .product()
708 }
709
710 /// This function calculate the Möbius `μ(n)` function of the input integer `n`
711 ///
712 /// This function behaves like `moebius_factorized(factorize(target))`.
713 /// If the input integer is very hard to factorize, it's better to use
714 /// the [`factors()`] function to control how the factorization is done, and then call
715 /// [`moebius_factorized()`].
716 ///
717 /// # Examples
718 ///
719 /// ```
720 /// use num_prime::nt_funcs::moebius;
721 ///
722 /// assert_eq!(moebius(&1u64), 1); // μ(1) = 1
723 /// assert_eq!(moebius(&2u64), -1); // μ(p) = -1
724 /// assert_eq!(moebius(&4u64), 0); // μ(p²) = 0
725 /// assert_eq!(moebius(&30u64), -1); // μ(2·3·5) = -1 (odd number of prime factors)
726 /// assert_eq!(moebius(&6u64), 1); // μ(2·3) = 1 (even number of prime factors)
727 /// ```
728 ///
729 /// # Panics
730 /// if the factorization failed on target.
731 pub fn moebius<T: PrimalityBase>(target: &T) -> i8
732 where
733 for<'r> &'r T: PrimalityRefBase<T>,
734 {
735 // remove factor 2
736 if target.is_even() {
737 let two = T::one() + T::one();
738 let four = &two + &two;
739 if (target % four).is_zero() {
740 return 0;
741 } else {
742 return -moebius(&(target / &two));
743 }
744 }
745
746 // look up tables when input is smaller than 256
747 if let Some(v) = (target - T::one()).to_u8() {
748 let m = MOEBIUS_ODD[(v >> 6) as usize];
749 let m = m & (3 << (v & 63));
750 let m = m >> (v & 63);
751 return m as i8 - 1;
752 }
753
754 // short cut for common primes
755 let three_sq = T::from_u8(9).unwrap();
756 let five_sq = T::from_u8(25).unwrap();
757 let seven_sq = T::from_u8(49).unwrap();
758 if (target % three_sq).is_zero()
759 || (target % five_sq).is_zero()
760 || (target % seven_sq).is_zero()
761 {
762 return 0;
763 }
764
765 // then try complete factorization
766 moebius_factorized(&factorize(target.clone()))
767 }
768
769 /// This function calculate the Möbius `μ(n)` function given the factorization
770 /// result of `n`
771 ///
772 /// # Examples
773 ///
774 /// ```
775 /// use num_prime::nt_funcs::{moebius_factorized, factorize};
776 ///
777 /// assert_eq!(moebius_factorized(&factorize(30u64)), -1); // 30 = 2·3·5
778 /// assert_eq!(moebius_factorized(&factorize(12u64)), 0); // 12 = 2²·3
779 /// assert_eq!(moebius_factorized(&factorize(6u64)), 1); // 6 = 2·3
780 /// ```
781 #[must_use]
782 pub fn moebius_factorized<T>(factors: &BTreeMap<T, usize>) -> i8 {
783 if factors.values().any(|exp| exp > &1) {
784 0
785 } else if factors.len() % 2 == 0 {
786 1
787 } else {
788 -1
789 }
790 }
791
792 /// Tests if the integer doesn't have any square number factor.
793 ///
794 /// # Examples
795 ///
796 /// ```
797 /// use num_prime::nt_funcs::is_square_free;
798 ///
799 /// assert!(is_square_free(&30u64)); // 30 = 2·3·5
800 /// assert!(!is_square_free(&12u64)); // 12 = 2²·3
801 /// assert!(is_square_free(&1u64));
802 /// ```
803 ///
804 /// # Panics
805 /// if the factorization failed on target.
806 pub fn is_square_free<T: PrimalityBase>(target: &T) -> bool
807 where
808 for<'r> &'r T: PrimalityRefBase<T>,
809 {
810 moebius(target) != 0
811 }
812
813 /// Returns the estimated bounds (low, high) of prime π function, such that
814 /// low <= π(target) <= high
815 ///
816 /// # Examples
817 ///
818 /// ```
819 /// use num_prime::nt_funcs::prime_pi_bounds;
820 ///
821 /// let (lo, hi) = prime_pi_bounds(&1_000_000u64);
822 /// // π(1_000_000) = 78498
823 /// assert!(lo <= 78498 && 78498 <= hi);
824 /// ```
825 ///
826 /// # Reference:
827 /// - \[1] Dusart, Pierre. "Estimates of Some Functions Over Primes without R.H."
828 /// [arxiv:1002.0442](http://arxiv.org/abs/1002.0442). 2010.
829 /// - \[2] Dusart, Pierre. "Explicit estimates of some functions over primes."
830 /// The Ramanujan Journal 45.1 (2018): 227-251.
831 pub fn prime_pi_bounds<T: ToPrimitive + FromPrimitive>(target: &T) -> (T, T) {
832 if let Some(x) = target.to_u64() {
833 // use existing primes and return exact value
834 if x <= u64::from(*SMALL_PRIMES.last().unwrap()) {
835 #[cfg(not(feature = "big-table"))]
836 let pos = SMALL_PRIMES.binary_search(&(x as u8));
837 #[cfg(feature = "big-table")]
838 let pos = SMALL_PRIMES.binary_search(&(x as u16));
839
840 let n = match pos {
841 Ok(p) => p + 1,
842 Err(p) => p,
843 };
844 return (T::from_usize(n).unwrap(), T::from_usize(n).unwrap());
845 }
846
847 // use function approximation
848 let n = x as f64;
849 let ln = n.ln();
850 let invln = ln.recip();
851
852 let lo = match () {
853 // [2] Collary 5.3
854 () if x >= 468_049 => n / (ln - 1. - invln),
855 // [2] Collary 5.2
856 () if x >= 88789 => n * invln * (1. + invln * (1. + 2. * invln)),
857 // [2] Collary 5.3
858 () if x >= 5393 => n / (ln - 1.),
859 // [2] Collary 5.2
860 () if x >= 599 => n * invln * (1. + invln),
861 // [2] Collary 5.2
862 () => n * invln,
863 };
864 let hi = match () {
865 // [2] Theorem 5.1, valid for x > 4e9, intersects at 7.3986e9
866 () if x >= 7_398_600_000 => {
867 n * invln * (1. + invln * (1. + invln * (2. + invln * 7.59)))
868 }
869 // [1] Theorem 6.9
870 () if x >= 2_953_652_287 => n * invln * (1. + invln * (1. + invln * 2.334)),
871 // [2] Collary 5.3, valid for x > 5.6, intersects at 5668
872 () if x >= 467_345 => n / (ln - 1. - 1.2311 * invln),
873 // [2] Collary 5.2, valid for x > 1, intersects at 29927
874 () if x >= 29927 => n * invln * (1. + invln * (1. + invln * 2.53816)),
875 // [2] Collary 5.3, valid for x > exp(1.112), intersects at 5668
876 () if x >= 5668 => n / (ln - 1.112),
877 // [2] Collary 5.2, valid for x > 1, intersects at 148
878 () if x >= 148 => n * invln * (1. + invln * 1.2762),
879 // [2] Collary 5.2, valid for x > 1
880 () => 1.25506 * n * invln,
881 };
882 (T::from_f64(lo).unwrap(), T::from_f64(hi).unwrap())
883 } else {
884 let n = target.to_f64().unwrap();
885 let ln = n.ln();
886 let invln = ln.recip();
887
888 // best bounds so far
889 let lo = n / (ln - 1. - invln);
890 let hi = n * invln * (1. + invln * (1. + invln * (2. + invln * 7.59)));
891 (T::from_f64(lo).unwrap(), T::from_f64(hi).unwrap())
892 }
893 }
894
895 /// Returns the estimated inclusive bounds (low, high) of the n-th prime. If the result
896 /// is larger than maximum of `T`, [None] will be returned.
897 ///
898 /// # Examples
899 ///
900 /// ```
901 /// use num_prime::nt_funcs::nth_prime_bounds;
902 ///
903 /// let (lo, hi) = nth_prime_bounds(&10_000u64).unwrap();
904 /// // The 10000th prime is 104729
905 /// assert!(lo <= 104729 && 104729 <= hi);
906 /// ```
907 ///
908 /// # Reference:
909 /// - \[1] Dusart, Pierre. "Estimates of Some Functions Over Primes without R.H."
910 /// arXiv preprint [arXiv:1002.0442](https://arxiv.org/abs/1002.0442) (2010).
911 /// - \[2] Rosser, J. Barkley, and Lowell Schoenfeld. "Approximate formulas for some
912 /// functions of prime numbers." Illinois Journal of Mathematics 6.1 (1962): 64-94.
913 /// - \[3] Dusart, Pierre. "The k th prime is greater than k (ln k+ ln ln k-1) for k≥ 2."
914 /// Mathematics of computation (1999): 411-415.
915 /// - \[4] Axler, Christian. ["New Estimates for the nth Prime Number."](https://www.emis.de/journals/JIS/VOL22/Axler/axler17.pdf)
916 /// Journal of Integer Sequences 22.2 (2019): 3.
917 /// - \[5] Axler, Christian. [Uber die Primzahl-Zählfunktion, die n-te Primzahl und verallgemeinerte Ramanujan-Primzahlen. Diss.](http://docserv.uniduesseldorf.de/servlets/DerivateServlet/Derivate-28284/pdfa-1b.pdf)
918 /// `PhD` thesis, Düsseldorf, 2013.
919 ///
920 /// Note that some of the results might depend on the Riemann Hypothesis. If you find
921 /// any prime that doesn't fall in the bound, then it might be a big discovery!
922 pub fn nth_prime_bounds<T: ToPrimitive + FromPrimitive>(target: &T) -> Option<(T, T)> {
923 if let Some(x) = target.to_usize() {
924 if x == 0 {
925 return Some((T::from_u8(0).unwrap(), T::from_u8(0).unwrap()));
926 }
927
928 // use existing primes and return exact value
929 if x <= SMALL_PRIMES.len() {
930 let p = SMALL_PRIMES[x - 1];
931
932 #[cfg(not(feature = "big-table"))]
933 return Some((T::from_u8(p).unwrap(), T::from_u8(p).unwrap()));
934
935 #[cfg(feature = "big-table")]
936 return Some((T::from_u16(p).unwrap(), T::from_u16(p).unwrap()));
937 }
938
939 // use function approximation
940 let n = x as f64;
941 let ln = n.ln();
942 let lnln = ln.ln();
943
944 let lo = match () {
945 // [4] Theroem 4, valid for x >= 2, intersects as 3.172e5
946 () if x >= 317_200 => {
947 n * (ln + lnln - 1. + (lnln - 2.) / ln
948 - (lnln * lnln - 6. * lnln + 11.321) / (2. * ln * ln))
949 }
950 // [1] Proposition 6.7, valid for x >= 3, intersects at 3520
951 () if x >= 3520 => n * (ln + lnln - 1. + (lnln - 2.1) / ln),
952 // [3] title
953 () => n * (ln + lnln - 1.),
954 };
955 let hi = match () {
956 // [4] Theroem 1, valid for x >= 46254381
957 () if x >= 46_254_381 => {
958 n * (ln + lnln - 1. + (lnln - 2.) / ln
959 - (lnln * lnln - 6. * lnln + 10.667) / (2. * ln * ln))
960 }
961 // [5] Korollar 2.11, valid for x >= 8009824
962 () if x >= 8_009_824 => {
963 n * (ln + lnln - 1. + (lnln - 2.) / ln
964 - (lnln * lnln - 6. * lnln + 10.273) / (2. * ln * ln))
965 }
966 // [1] Proposition 6.6
967 () if x >= 688_383 => n * (ln + lnln - 1. + (lnln - 2.) / ln),
968 // [1] Lemma 6.5
969 () if x >= 178_974 => n * (ln + lnln - 1. + (lnln - 1.95) / ln),
970 // [3] in "Further Results"
971 () if x >= 39017 => n * (ln + lnln - 0.9484),
972 // [3] in "Further Results"
973 () if x >= 27076 => n * (ln + lnln - 1. + (lnln - 1.8) / ln),
974 // [2] Theorem 3, valid for x >= 20
975 () => n * (ln + lnln - 0.5),
976 };
977 Some((T::from_f64(lo)?, T::from_f64(hi)?))
978 } else {
979 let n = target.to_f64().unwrap();
980 let ln = n.ln();
981 let lnln = ln.ln();
982
983 // best bounds so far
984 let lo = n
985 * (ln + lnln - 1. + (lnln - 2.) / ln
986 - (lnln * lnln - 6. * lnln + 11.321) / (2. * ln * ln));
987 let hi = n
988 * (ln + lnln - 1. + (lnln - 2.) / ln
989 - (lnln * lnln - 6. * lnln + 10.667) / (2. * ln * ln));
990 Some((T::from_f64(lo)?, T::from_f64(hi)?))
991 }
992 }
993
994 /// Test if the target is a safe prime under [Sophie German's definition](https://en.wikipedia.org/wiki/Safe_and_Sophie_Germain_primes). It will use the
995 /// [strict primality test configuration][FactorizationConfig::strict()].
996 ///
997 /// # Examples
998 ///
999 /// ```
1000 /// use num_prime::nt_funcs::is_safe_prime;
1001 ///
1002 /// assert!(is_safe_prime(&5u64).probably()); // (5-1)/2 = 2, prime
1003 /// assert!(is_safe_prime(&7u64).probably()); // (7-1)/2 = 3, prime
1004 /// assert!(is_safe_prime(&23u64).probably()); // (23-1)/2 = 11, prime
1005 /// assert!(!is_safe_prime(&13u64).probably()); // (13-1)/2 = 6, not prime
1006 /// ```
1007 pub fn is_safe_prime<T: PrimalityBase>(target: &T) -> Primality
1008 where
1009 for<'r> &'r T: PrimalityRefBase<T>,
1010 {
1011 let buf = NaiveBuffer::new();
1012 let config = Some(PrimalityTestConfig::strict());
1013
1014 // test (n-1)/2 first since its smaller
1015 let sophie_p = buf.is_prime(&(target >> 1), config);
1016 if matches!(sophie_p, Primality::No) {
1017 return sophie_p;
1018 }
1019
1020 // and then test target itself
1021 let target_p = buf.is_prime(target, config);
1022 target_p & sophie_p
1023 }
1024
1025 /// Find the first prime number larger than `target`. If the result causes an overflow,
1026 /// then [None] will be returned
1027 ///
1028 /// # Examples
1029 ///
1030 /// ```
1031 /// use num_prime::nt_funcs::next_prime;
1032 ///
1033 /// assert_eq!(next_prime(&13u32, None), Some(17));
1034 /// assert_eq!(next_prime(&1000u32, None), Some(1009));
1035 /// ```
1036 #[cfg(not(feature = "big-table"))]
1037 pub fn next_prime<T: PrimalityBase + CheckedAdd>(
1038 target: &T,
1039 config: Option<PrimalityTestConfig>,
1040 ) -> Option<T>
1041 where
1042 for<'r> &'r T: PrimalityRefBase<T>,
1043 {
1044 // first search in small primes
1045 if let Some(x) = target.to_u8() {
1046 return match SMALL_PRIMES.binary_search(&x) {
1047 Ok(pos) => {
1048 if pos + 1 == SMALL_PRIMES.len() {
1049 T::from_u64(SMALL_PRIMES_NEXT)
1050 } else {
1051 T::from_u8(SMALL_PRIMES[pos + 1])
1052 }
1053 }
1054 Err(pos) if pos < SMALL_PRIMES.len() => T::from_u8(SMALL_PRIMES[pos]),
1055 Err(_) => T::from_u64(SMALL_PRIMES_NEXT),
1056 };
1057 }
1058
1059 // then moving along the wheel
1060 let mut i = (target % T::from_u8(WHEEL_SIZE).unwrap()).to_u8().unwrap();
1061 let mut t = target.clone();
1062 loop {
1063 let offset = WHEEL_NEXT[i as usize];
1064 t = t.checked_add(&T::from_u8(offset).unwrap())?;
1065 i = i.addm(offset, &WHEEL_SIZE);
1066 if is_prime(&t, config).probably() {
1067 break Some(t);
1068 }
1069 }
1070 }
1071
1072 /// Find the first prime number larger than `target`. If the result causes an overflow,
1073 /// then [None] will be returned
1074 ///
1075 /// # Examples
1076 ///
1077 /// ```
1078 /// use num_prime::nt_funcs::next_prime;
1079 ///
1080 /// assert_eq!(next_prime(&13u32, None), Some(17));
1081 /// assert_eq!(next_prime(&1000u32, None), Some(1009));
1082 /// ```
1083 #[cfg(feature = "big-table")]
1084 pub fn next_prime<T: PrimalityBase + CheckedAdd>(
1085 target: &T,
1086 config: Option<PrimalityTestConfig>,
1087 ) -> Option<T>
1088 where
1089 for<'r> &'r T: PrimalityRefBase<T>,
1090 {
1091 // first search in small primes
1092 if target <= &T::from_u8(255).unwrap() // shortcut for T=u8
1093 || target < &T::from_u16(*SMALL_PRIMES.last().unwrap()).unwrap()
1094 {
1095 let next = match SMALL_PRIMES.binary_search(&target.to_u16().unwrap()) {
1096 Ok(pos) => SMALL_PRIMES[pos + 1],
1097 Err(pos) => SMALL_PRIMES[pos],
1098 };
1099 return T::from_u16(next);
1100 }
1101
1102 // then moving along the wheel
1103 let mut i = (target % T::from_u16(WHEEL_SIZE).unwrap())
1104 .to_u16()
1105 .unwrap();
1106 let mut t = target.clone();
1107 loop {
1108 let offset = WHEEL_NEXT[i as usize];
1109 t = t.checked_add(&T::from_u8(offset).unwrap())?;
1110 i = i.addm(u16::from(offset), &WHEEL_SIZE);
1111 if is_prime(&t, config).probably() {
1112 break Some(t);
1113 }
1114 }
1115 }
1116
1117 /// Find the first prime number smaller than `target`. If target is less than 3, then [None]
1118 /// will be returned.
1119 ///
1120 /// # Examples
1121 ///
1122 /// ```
1123 /// use num_prime::nt_funcs::prev_prime;
1124 ///
1125 /// assert_eq!(prev_prime(&13u32, None), Some(11));
1126 /// assert_eq!(prev_prime(&1000u32, None), Some(997));
1127 /// assert_eq!(prev_prime(&2u32, None), None);
1128 /// ```
1129 #[cfg(not(feature = "big-table"))]
1130 pub fn prev_prime<T: PrimalityBase>(target: &T, config: Option<PrimalityTestConfig>) -> Option<T>
1131 where
1132 for<'r> &'r T: PrimalityRefBase<T>,
1133 {
1134 if target <= &(T::one() + T::one()) {
1135 return None;
1136 }
1137
1138 // first search in small primes
1139 if let Some(x) = target.to_u8() {
1140 let next = match SMALL_PRIMES.binary_search(&x) {
1141 Ok(pos) => SMALL_PRIMES[pos - 1],
1142 Err(pos) => SMALL_PRIMES[pos - 1],
1143 };
1144 return Some(T::from_u8(next).unwrap());
1145 }
1146
1147 // then moving along the wheel
1148 let mut i = (target % T::from_u8(WHEEL_SIZE).unwrap()).to_u8().unwrap();
1149 let mut t = target.clone();
1150 loop {
1151 let offset = WHEEL_PREV[i as usize];
1152 t = t - T::from_u8(offset).unwrap();
1153 i = i.subm(offset, &WHEEL_SIZE);
1154 if is_prime(&t, config).probably() {
1155 break Some(t);
1156 }
1157 }
1158 }
1159
1160 /// Find the first prime number smaller than `target`. If target is less than 3, then [None]
1161 /// will be returned.
1162 ///
1163 /// # Examples
1164 ///
1165 /// ```
1166 /// use num_prime::nt_funcs::prev_prime;
1167 ///
1168 /// assert_eq!(prev_prime(&13u32, None), Some(11));
1169 /// assert_eq!(prev_prime(&1000u32, None), Some(997));
1170 /// assert_eq!(prev_prime(&2u32, None), None);
1171 /// ```
1172 #[cfg(feature = "big-table")]
1173 pub fn prev_prime<T: PrimalityBase>(target: &T, config: Option<PrimalityTestConfig>) -> Option<T>
1174 where
1175 for<'r> &'r T: PrimalityRefBase<T>,
1176 {
1177 if target <= &(T::one() + T::one()) {
1178 return None;
1179 }
1180
1181 // first search in small primes
1182 if target <= &T::from_u8(255).unwrap() // shortcut for u8
1183 || target < &T::from_u16(*SMALL_PRIMES.last().unwrap()).unwrap()
1184 {
1185 let next = match SMALL_PRIMES.binary_search(&target.to_u16().unwrap()) {
1186 Ok(pos) => SMALL_PRIMES[pos - 1],
1187 Err(pos) => SMALL_PRIMES[pos - 1],
1188 };
1189 return Some(T::from_u16(next).unwrap());
1190 }
1191
1192 // then moving along the wheel
1193 let mut i = (target % T::from_u16(WHEEL_SIZE).unwrap())
1194 .to_u16()
1195 .unwrap();
1196 let mut t = target.clone();
1197 loop {
1198 let offset = WHEEL_PREV[i as usize];
1199 t = t - T::from_u8(offset).unwrap();
1200 i = i.subm(u16::from(offset), &WHEEL_SIZE);
1201 if is_prime(&t, config).probably() {
1202 break Some(t);
1203 }
1204 }
1205 }
1206
1207 /// Estimate the value of prime π() function by averaging the estimated bounds.
1208 ///
1209 /// # Examples
1210 ///
1211 /// ```
1212 /// use num_prime::nt_funcs::{prime_pi_est, prime_pi_bounds};
1213 ///
1214 /// let est = prime_pi_est(&1_000_000u64);
1215 /// let (lo, hi) = prime_pi_bounds(&1_000_000u64);
1216 /// assert!(lo <= est && est <= hi);
1217 /// ```
1218 #[cfg(not(feature = "big-table"))]
1219 pub fn prime_pi_est<T: Num + ToPrimitive + FromPrimitive>(target: &T) -> T {
1220 let (lo, hi) = prime_pi_bounds(target);
1221 (lo + hi) / T::from_u8(2).unwrap()
1222 }
1223
1224 /// Estimate the value of prime `π()` function by Riemann's R function. The estimation
1225 /// error is roughly of scale O(sqrt(x)log(x)).
1226 ///
1227 /// Reference: <https://primes.utm.edu/howmany.html#better>
1228 ///
1229 /// # Examples
1230 ///
1231 /// ```
1232 /// use num_prime::nt_funcs::{prime_pi_est, prime_pi_bounds};
1233 ///
1234 /// let est = prime_pi_est(&1_000_000u64);
1235 /// let (lo, hi) = prime_pi_bounds(&1_000_000u64);
1236 /// assert!(lo <= est && est <= hi);
1237 /// ```
1238 #[cfg(feature = "big-table")]
1239 pub fn prime_pi_est<T: ToPrimitive + FromPrimitive>(target: &T) -> T {
1240 // shortcut
1241 if let Some(x) = target.to_u16() {
1242 if x <= { *SMALL_PRIMES.last().unwrap() } {
1243 let (lo, hi) = prime_pi_bounds(&x);
1244 debug_assert_eq!(lo, hi);
1245 return T::from_u16(lo).unwrap();
1246 }
1247 }
1248
1249 // Gram expansion with logarithm arithmetics
1250 let lnln = target.to_f64().unwrap().ln().ln();
1251 let mut total = 0f64;
1252 let mut lnp = 0f64; // k*ln(ln(x))
1253 let mut lnfac = 0f64; // ln(k!)
1254
1255 for k in 1usize..100 {
1256 lnp += lnln;
1257 let lnk = (k as f64).ln();
1258 lnfac += lnk;
1259 let lnzeta = if k > 64 { 0f64 } else { ZETA_LOG_TABLE[k - 1] };
1260 let t = lnp - lnk - lnfac - lnzeta;
1261 if t < -4. {
1262 // stop if the increment is too small
1263 break;
1264 }
1265 total += t.exp();
1266 }
1267 T::from_f64(total + 1f64).unwrap()
1268 }
1269
1270 /// Estimate the value of nth prime by bisecting on [`prime_pi_est`].
1271 /// If the result is larger than maximum of `T`, [None] will be returned.
1272 ///
1273 /// # Examples
1274 ///
1275 /// ```
1276 /// use num_prime::nt_funcs::{nth_prime_est, nth_prime_bounds};
1277 ///
1278 /// let est = nth_prime_est(&10_000u64).unwrap();
1279 /// let (lo, hi) = nth_prime_bounds(&10_000u64).unwrap();
1280 /// assert!(lo <= est && est <= hi);
1281 /// ```
1282 pub fn nth_prime_est<T: ToPrimitive + FromPrimitive + Num + PartialOrd>(target: &T) -> Option<T>
1283 where
1284 for<'r> &'r T: RefNum<T>,
1285 {
1286 let (mut lo, mut hi) = nth_prime_bounds(target)?;
1287 if lo == hi {
1288 return Some(lo);
1289 }
1290
1291 while lo != &hi - T::from_u8(1).unwrap() {
1292 let x = (&lo + &hi) / T::from_u8(2).unwrap();
1293 let mid = prime_pi_est(&x);
1294 if &mid < target {
1295 lo = x;
1296 } else if &mid > target {
1297 hi = x;
1298 } else {
1299 return Some(x);
1300 }
1301 }
1302 Some(lo)
1303 }
1304
1305 // TODO: More functions
1306 // REF: http://www.numbertheory.org/gnubc/bc_programs.html
1307 // REF: https://github.com/TilmanNeumann/java-math-library
1308 // - is_smooth: checks if the smoothness bound is at least b
1309 // - euler_phi: Euler's totient function
1310 // - jordan_tot: Jordan's totient function
1311 // Others include Louiville function, Mangoldt function, Dedekind psi function, Dickman rho function, etc..
1312
1313 #[cfg(test)]
1314 mod tests {
1315 use super::*;
1316 use rand::{prelude::SliceRandom, random};
1317 use std::iter::FromIterator;
1318
1319 #[test]
1320 fn is_prime64_test() {
1321 // test small primes
1322 for x in 2..100 {
1323 assert_eq!(SMALL_PRIMES.contains(&x), is_prime64(u64::from(x)));
1324 }
1325 assert!(is_prime64(677));
1326
1327 // from PR #7
1328 assert!(!is_prime64(9773));
1329 assert!(!is_prime64(13357));
1330 assert!(!is_prime64(18769));
1331
1332 // some large primes
1333 assert!(is_prime64(6_469_693_333));
1334 assert!(is_prime64(13_756_265_695_458_089_029));
1335 assert!(is_prime64(13_496_181_268_022_124_907));
1336 assert!(is_prime64(10_953_742_525_620_032_441));
1337 assert!(is_prime64(17_908_251_027_575_790_097));
1338
1339 // primes from examples in Bradley Berg's hash method
1340 assert!(is_prime64(480_194_653));
1341 assert!(!is_prime64(20_074_069));
1342 assert!(is_prime64(8_718_775_377_449));
1343 assert!(is_prime64(3_315_293_452_192_821_991));
1344 assert!(!is_prime64(8_651_776_913_431));
1345 assert!(!is_prime64(1_152_965_996_591_997_761));
1346
1347 // false positives reported by JASory (#4)
1348 assert!(!is_prime64(600_437_059_821_397));
1349 assert!(!is_prime64(3_866_032_210_719_337));
1350 assert!(!is_prime64(4_100_599_722_623_587));
1351
1352 // ensure no factor for 100 random primes
1353 let mut rng = rand::thread_rng();
1354 for _ in 0..100 {
1355 let x = random();
1356 if !is_prime64(x) {
1357 continue;
1358 }
1359 assert_ne!(x % u64::from(*SMALL_PRIMES.choose(&mut rng).unwrap()), 0);
1360 }
1361
1362 // create random composites
1363 for _ in 0..100 {
1364 let x = u64::from(random::<u32>());
1365 let y = u64::from(random::<u32>());
1366 assert!(!is_prime64(x * y));
1367 }
1368 }
1369
1370 #[test]
1371 fn factorize64_test() {
1372 // some simple cases
1373 let fac4095 = BTreeMap::from_iter([(3, 2), (5, 1), (7, 1), (13, 1)]);
1374 let fac = factorize64(4095);
1375 assert_eq!(fac, fac4095);
1376
1377 let fac123456789 = BTreeMap::from_iter([(3, 2), (3803, 1), (3607, 1)]);
1378 let fac = factorize64(123_456_789);
1379 assert_eq!(fac, fac123456789);
1380
1381 let fac1_17 = BTreeMap::from_iter([(2_071_723, 1), (5_363_222_357, 1)]);
1382 let fac = factorize64(11_111_111_111_111_111);
1383 assert_eq!(fac, fac1_17);
1384
1385 // perfect powers
1386 for exp in 2u32..5 {
1387 assert_eq!(
1388 factorize128(8167u128.pow(exp)),
1389 BTreeMap::from_iter([(8167, exp as usize)])
1390 );
1391 }
1392
1393 // 100 random factorization tests
1394 for _ in 0..100 {
1395 let x = random();
1396 let fac = factorize64(x);
1397 let mut prod = 1;
1398 for (p, exp) in fac {
1399 assert!(
1400 is_prime64(p),
1401 "factorization result should have prime factors! (get {})",
1402 p
1403 );
1404 prod *= p.pow(exp as u32);
1405 }
1406 assert_eq!(x, prod, "factorization check failed! ({x} != {prod})");
1407 }
1408 }
1409
1410 #[test]
1411 fn factorize128_test() {
1412 // some simple cases
1413 let fac_primorial19 =
1414 BTreeMap::from_iter(SMALL_PRIMES.iter().take(19).map(|&p| (u128::from(p), 1)));
1415 let fac = factorize128(7_858_321_551_080_267_055_879_090);
1416 assert_eq!(fac, fac_primorial19);
1417
1418 let fac_smallbig = BTreeMap::from_iter([(167, 1), (2_417_851_639_229_258_349_412_369, 1)]);
1419 let fac = factorize128(403_781_223_751_286_144_351_865_623);
1420 assert_eq!(fac, fac_smallbig);
1421
1422 // perfect powers
1423 for exp in 5u32..10 {
1424 // 2^64 < 8167^5 < 8167^9 < 2^128
1425 assert_eq!(
1426 factorize128(8167u128.pow(exp)),
1427 BTreeMap::from_iter([(8167, exp as usize)])
1428 );
1429 }
1430
1431 // random factorization tests
1432 for _ in 0..4 {
1433 let x = random::<u128>() >> 28; // test 100 bit numbers
1434 let fac = factorize128(x);
1435 let mut prod = 1;
1436 for (p, exp) in fac {
1437 assert!(
1438 is_prime(&p, None).probably(),
1439 "factorization result should have prime factors! (get {})",
1440 p
1441 );
1442 prod *= p.pow(exp as u32);
1443 }
1444 assert_eq!(x, prod, "factorization check failed! ({x} != {prod})");
1445 }
1446 }
1447
1448 #[test]
1449 fn is_safe_prime_test() {
1450 // OEIS:A005385
1451 let safe_primes = [
1452 5u16, 7, 11, 23, 47, 59, 83, 107, 167, 179, 227, 263, 347, 359, 383, 467, 479, 503,
1453 563, 587, 719, 839, 863, 887, 983, 1019, 1187, 1283, 1307, 1319, 1367, 1439, 1487,
1454 1523, 1619, 1823, 1907,
1455 ];
1456 for p in SMALL_PRIMES {
1457 #[allow(clippy::unnecessary_cast)]
1458 let p = p as u16;
1459 if p > 1500 {
1460 break;
1461 }
1462 assert_eq!(
1463 is_safe_prime(&p).probably(),
1464 safe_primes.iter().any(|v| &p == v)
1465 );
1466 }
1467 }
1468
1469 #[test]
1470 fn moebius_test() {
1471 // test small examples
1472 let mu20: [i8; 20] = [
1473 1, -1, -1, 0, -1, 1, -1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1, 0, -1, 0,
1474 ];
1475 for (i, &expected) in mu20.iter().enumerate() {
1476 assert_eq!(moebius(&(i + 1)), expected, "moebius on {i}");
1477 }
1478
1479 // some square numbers
1480 assert_eq!(moebius(&1024u32), 0);
1481 assert_eq!(moebius(&(8081u32 * 8081)), 0);
1482
1483 // sphenic numbers
1484 let sphenic3: [u8; 20] = [
1485 30, 42, 66, 70, 78, 102, 105, 110, 114, 130, 138, 154, 165, 170, 174, 182, 186, 190,
1486 195, 222,
1487 ]; // OEIS:A007304
1488 for &val in &sphenic3 {
1489 assert_eq!(moebius(&val), -1i8, "moebius on {val}");
1490 }
1491 let sphenic5: [u16; 23] = [
1492 2310, 2730, 3570, 3990, 4290, 4830, 5610, 6006, 6090, 6270, 6510, 6630, 7410, 7590,
1493 7770, 7854, 8610, 8778, 8970, 9030, 9282, 9570, 9690,
1494 ]; // OEIS:A046387
1495 for &val in sphenic5.iter().take(20) {
1496 assert_eq!(moebius(&val), -1i8, "moebius on {val}");
1497 }
1498 }
1499
1500 #[test]
1501 fn prime_pi_bounds_test() {
1502 fn check(n: u64, pi: u64) {
1503 let (lo, hi) = prime_pi_bounds(&n);
1504 let est = prime_pi_est(&n);
1505 assert!(
1506 lo <= pi && pi <= hi,
1507 "fail to satisfy {} <= pi({}) = {} <= {}",
1508 lo,
1509 n,
1510 pi,
1511 hi
1512 );
1513 assert!(lo <= est && est <= hi);
1514 }
1515
1516 // test with sieved primes
1517 let mut pb = NaiveBuffer::new();
1518 let mut last = 0;
1519 for (i, p) in pb.primes(100_000).copied().enumerate() {
1520 for j in last..p {
1521 check(j, i as u64);
1522 }
1523 last = p;
1524 }
1525
1526 // test with some known cases with input as 10^n, OEIS:A006880
1527 let pow10_values = [
1528 0,
1529 4,
1530 25,
1531 168,
1532 1229,
1533 9592,
1534 78498,
1535 664_579,
1536 5_761_455,
1537 50_847_534,
1538 455_052_511,
1539 4_118_054_813,
1540 37_607_912_018,
1541 346_065_536_839,
1542 3_204_941_750_802,
1543 29_844_570_422_669,
1544 279_238_341_033_925,
1545 2_623_557_157_654_233,
1546 ];
1547 for (exponent, gt) in pow10_values.iter().enumerate() {
1548 let n = 10u64.pow(exponent as u32);
1549 check(n, *gt);
1550 }
1551 }
1552
1553 #[test]
1554 fn nth_prime_bounds_test() {
1555 fn check(n: u64, p: u64) {
1556 let (lo, hi) = super::nth_prime_bounds(&n).unwrap();
1557 assert!(
1558 lo <= p && p <= hi,
1559 "fail to satisfy: {} <= {}-th prime = {} <= {}",
1560 lo,
1561 n,
1562 p,
1563 hi
1564 );
1565 let est = super::nth_prime_est(&n).unwrap();
1566 assert!(lo <= est && est <= hi);
1567 }
1568
1569 // test with sieved primes
1570 let mut pb = NaiveBuffer::new();
1571 for (i, p) in pb.primes(100_000).copied().enumerate() {
1572 check(i as u64 + 1, p);
1573 }
1574
1575 // test with some known cases with input as 10^n, OEIS:A006988
1576 let pow10_values = [
1577 2,
1578 29,
1579 541,
1580 7919,
1581 104_729,
1582 1_299_709,
1583 15_485_863,
1584 179_424_673,
1585 2_038_074_743,
1586 22_801_763_489,
1587 252_097_800_623,
1588 2_760_727_302_517,
1589 29_996_224_275_833,
1590 323_780_508_946_331,
1591 3_475_385_758_524_527,
1592 37_124_508_045_065_437,
1593 ];
1594 for (exponent, nth_prime) in pow10_values.iter().enumerate() {
1595 let n = 10u64.pow(exponent as u32);
1596 check(n, *nth_prime);
1597 }
1598 }
1599
1600 #[test]
1601 fn prev_next_test() {
1602 assert_eq!(prev_prime(&2u32, None), None);
1603
1604 // prime table boundary test
1605 assert_eq!(prev_prime(&257u16, None), Some(251));
1606 assert_eq!(next_prime(&251u16, None), Some(257));
1607 assert_eq!(next_prime(&251u8, None), None);
1608 assert_eq!(prev_prime(&8167u16, None), Some(8161));
1609 assert_eq!(next_prime(&8161u16, None), Some(8167));
1610
1611 // OEIS:A077800
1612 let twine_primes: [(u32, u32); 8] = [
1613 (2, 3), // not exactly twine
1614 (3, 5),
1615 (5, 7),
1616 (11, 13),
1617 (17, 19),
1618 (29, 31),
1619 (41, 43),
1620 (617, 619),
1621 ];
1622 for (p1, p2) in twine_primes {
1623 assert_eq!(prev_prime(&p2, None).unwrap(), p1);
1624 assert_eq!(next_prime(&p1, None).unwrap(), p2);
1625 }
1626
1627 let adj10_primes: [(u32, u32); 7] = [
1628 (7, 11),
1629 (97, 101),
1630 (997, 1009),
1631 (9973, 10007),
1632 (99991, 100_003),
1633 (999_983, 1_000_003),
1634 (9_999_991, 10_000_019),
1635 ];
1636 for (i, (p1, p2)) in adj10_primes.iter().enumerate() {
1637 assert_eq!(prev_prime(p2, None).unwrap(), *p1);
1638 assert_eq!(next_prime(p1, None).unwrap(), *p2);
1639
1640 let pow = 10u32.pow((i + 1) as u32);
1641 assert_eq!(prev_prime(&pow, None).unwrap(), *p1);
1642 assert_eq!(next_prime(&pow, None).unwrap(), *p2);
1643 }
1644 }
1645
1646 #[test]
1647 fn factors_overflow_test() {
1648 // Test for issue #23: multiplication overflow in one_line factorization
1649 // This should not panic in debug builds
1650 let problematic_number = 0x3ffffffffffffff8u64;
1651 let (factors_map, cofactors) = factors(problematic_number, None);
1652
1653 // Verify that we get the correct factorization: 2^3 × 179951 × 3203431780337
1654 // The function should not panic due to overflow
1655 assert!(!factors_map.is_empty(), "Should find at least some factors");
1656
1657 // Verify the product of all factors equals the original number
1658 let mut product = 1u64;
1659 for (factor, count) in &factors_map {
1660 product = product
1661 .checked_mul(factor.pow(*count as u32))
1662 .expect("Product computation should not overflow");
1663 }
1664 if let Some(ref remaining) = cofactors {
1665 for cofactor in remaining {
1666 product = product
1667 .checked_mul(*cofactor)
1668 .expect("Product computation should not overflow");
1669 }
1670 }
1671 assert_eq!(
1672 product, problematic_number,
1673 "Product of factors should equal original number"
1674 );
1675 }
1676 }