num_bigint_dig/
biguint.rs

1#[allow(deprecated, unused_imports)]
2use alloc::borrow::Cow;
3use alloc::string::String;
4use alloc::vec::Vec;
5use core::cmp::Ordering::{self, Equal, Greater, Less};
6use core::default::Default;
7use core::hash::{Hash, Hasher};
8use core::iter::{Product, Sum};
9use core::ops::{
10    Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign,
11    Mul, MulAssign, Neg, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign,
12};
13use core::str::{self, FromStr};
14use core::{cmp, fmt, mem};
15use core::{f32, f64};
16use core::{u32, u64, u8};
17
18#[cfg(feature = "serde")]
19use serde;
20
21#[cfg(feature = "zeroize")]
22use zeroize::Zeroize;
23
24#[cfg(feature = "std")]
25fn sqrt(a: f64) -> f64 {
26    a.sqrt()
27}
28
29#[cfg(not(feature = "std"))]
30fn sqrt(a: f64) -> f64 {
31    libm::sqrt(a)
32}
33
34#[cfg(feature = "std")]
35fn ln(a: f64) -> f64 {
36    a.ln()
37}
38
39#[cfg(not(feature = "std"))]
40fn ln(a: f64) -> f64 {
41    libm::log(a)
42}
43
44#[cfg(feature = "std")]
45fn cbrt(a: f64) -> f64 {
46    a.cbrt()
47}
48
49#[cfg(not(feature = "std"))]
50fn cbrt(a: f64) -> f64 {
51    libm::cbrt(a)
52}
53
54#[cfg(feature = "std")]
55fn exp(a: f64) -> f64 {
56    a.exp()
57}
58
59#[cfg(not(feature = "std"))]
60fn exp(a: f64) -> f64 {
61    libm::exp(a)
62}
63
64use crate::integer::{Integer, Roots};
65use num_traits::float::FloatCore;
66use num_traits::{
67    CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, FromPrimitive, Num, One, Pow, ToPrimitive,
68    Unsigned, Zero,
69};
70
71use crate::BigInt;
72
73use crate::big_digit::{self, BigDigit};
74
75use smallvec::SmallVec;
76
77#[path = "monty.rs"]
78mod monty;
79
80use self::monty::monty_modpow;
81use super::VEC_SIZE;
82use crate::algorithms::{__add2, __sub2rev, add2, sub2, sub2rev};
83use crate::algorithms::{biguint_shl, biguint_shr};
84use crate::algorithms::{cmp_slice, fls, idiv_ceil, ilog2};
85use crate::algorithms::{div_rem, div_rem_digit, mac_with_carry, mul3, scalar_mul};
86use crate::algorithms::{extended_gcd, mod_inverse};
87use crate::traits::{ExtendedGcd, ModInverse};
88
89use crate::ParseBigIntError;
90use crate::UsizePromotion;
91
92/// A big unsigned integer type.
93#[derive(Clone, Debug)]
94pub struct BigUint {
95    pub(crate) data: SmallVec<[BigDigit; VEC_SIZE]>,
96}
97
98impl PartialEq for BigUint {
99    #[inline]
100    fn eq(&self, other: &BigUint) -> bool {
101        match self.cmp(other) {
102            Equal => true,
103            _ => false,
104        }
105    }
106}
107impl Eq for BigUint {}
108
109impl Hash for BigUint {
110    fn hash<H: Hasher>(&self, state: &mut H) {
111        self.data.hash(state);
112    }
113}
114
115impl PartialOrd for BigUint {
116    #[inline]
117    fn partial_cmp(&self, other: &BigUint) -> Option<Ordering> {
118        Some(self.cmp(other))
119    }
120}
121
122impl Ord for BigUint {
123    #[inline]
124    fn cmp(&self, other: &BigUint) -> Ordering {
125        cmp_slice(&self.data[..], &other.data[..])
126    }
127}
128
129impl Default for BigUint {
130    #[inline]
131    fn default() -> BigUint {
132        Zero::zero()
133    }
134}
135
136#[cfg(feature = "zeroize")]
137impl Zeroize for BigUint {
138    fn zeroize(&mut self) {
139        self.data.as_mut().zeroize();
140    }
141}
142
143impl fmt::Display for BigUint {
144    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
145        f.pad_integral(true, "", &self.to_str_radix(10))
146    }
147}
148
149impl fmt::LowerHex for BigUint {
150    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
151        f.pad_integral(true, "0x", &self.to_str_radix(16))
152    }
153}
154
155impl fmt::UpperHex for BigUint {
156    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
157        let mut s = self.to_str_radix(16);
158        s.make_ascii_uppercase();
159        f.pad_integral(true, "0x", &s)
160    }
161}
162
163impl fmt::Binary for BigUint {
164    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
165        f.pad_integral(true, "0b", &self.to_str_radix(2))
166    }
167}
168
169impl fmt::Octal for BigUint {
170    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
171        f.pad_integral(true, "0o", &self.to_str_radix(8))
172    }
173}
174
175impl FromStr for BigUint {
176    type Err = ParseBigIntError;
177
178    #[inline]
179    fn from_str(s: &str) -> Result<BigUint, ParseBigIntError> {
180        BigUint::from_str_radix(s, 10)
181    }
182}
183
184// Convert from a power of two radix (bits == ilog2(radix)) where bits evenly divides
185// BigDigit::BITS
186fn from_bitwise_digits_le(v: &[u8], bits: usize) -> BigUint {
187    debug_assert!(!v.is_empty() && bits <= 8 && big_digit::BITS % bits == 0);
188    debug_assert!(v.iter().all(|&c| (c as BigDigit) < (1 << bits)));
189
190    let digits_per_big_digit = big_digit::BITS / bits;
191
192    let data = v
193        .chunks(digits_per_big_digit)
194        .map(|chunk| {
195            chunk
196                .iter()
197                .rev()
198                .fold(0, |acc, &c| (acc << bits) | c as BigDigit)
199        })
200        .collect();
201
202    BigUint::new_native(data)
203}
204
205// Convert from a power of two radix (bits == ilog2(radix)) where bits doesn't evenly divide
206// BigDigit::BITS
207fn from_inexact_bitwise_digits_le(v: &[u8], bits: usize) -> BigUint {
208    debug_assert!(!v.is_empty() && bits <= 8 && big_digit::BITS % bits != 0);
209    debug_assert!(v.iter().all(|&c| (c as BigDigit) < (1 << bits)));
210
211    let big_digits = (v.len() * bits + big_digit::BITS - 1) / big_digit::BITS;
212    let mut data = SmallVec::with_capacity(big_digits);
213
214    let mut d = 0;
215    let mut dbits = 0; // number of bits we currently have in d
216
217    // walk v accumululating bits in d; whenever we accumulate big_digit::BITS in d, spit out a
218    // big_digit:
219    for &c in v {
220        d |= (c as BigDigit) << dbits;
221        dbits += bits;
222
223        if dbits >= big_digit::BITS {
224            data.push(d);
225            dbits -= big_digit::BITS;
226            // if dbits was > big_digit::BITS, we dropped some of the bits in c (they couldn't fit
227            // in d) - grab the bits we lost here:
228            d = (c as BigDigit) >> (bits - dbits);
229        }
230    }
231
232    if dbits > 0 {
233        debug_assert!(dbits < big_digit::BITS);
234        data.push(d as BigDigit);
235    }
236
237    BigUint::new_native(data)
238}
239
240// Read little-endian radix digits
241fn from_radix_digits_be(v: &[u8], radix: u32) -> BigUint {
242    debug_assert!(!v.is_empty() && !radix.is_power_of_two());
243    debug_assert!(v.iter().all(|&c| (c as u32) < radix));
244
245    // Estimate how big the result will be, so we can pre-allocate it.
246    let bits = ilog2(radix) * v.len();
247    let big_digits = idiv_ceil(bits, big_digit::BITS);
248    let mut data = SmallVec::with_capacity(big_digits);
249
250    let (base, power) = get_radix_base(radix);
251    let radix = radix as BigDigit;
252
253    let r = v.len() % power;
254    let i = if r == 0 { power } else { r };
255    let (head, tail) = v.split_at(i);
256
257    let first = head.iter().fold(0, |acc, &d| acc * radix + d as BigDigit);
258    data.push(first);
259
260    debug_assert!(tail.len() % power == 0);
261    for chunk in tail.chunks(power) {
262        if data.last() != Some(&0) {
263            data.push(0);
264        }
265
266        let mut carry = 0;
267        for d in data.iter_mut() {
268            *d = mac_with_carry(0, *d, base, &mut carry);
269        }
270        debug_assert!(carry == 0);
271
272        let n = chunk.iter().fold(0, |acc, &d| acc * radix + d as BigDigit);
273        add2(&mut data, &[n]);
274    }
275
276    BigUint::new_native(data)
277}
278
279impl Num for BigUint {
280    type FromStrRadixErr = ParseBigIntError;
281
282    /// Creates and initializes a `BigUint`.
283    fn from_str_radix(s: &str, radix: u32) -> Result<BigUint, ParseBigIntError> {
284        assert!(2 <= radix && radix <= 36, "The radix must be within 2...36");
285        let mut s = s;
286        if s.starts_with('+') {
287            let tail = &s[1..];
288            if !tail.starts_with('+') {
289                s = tail
290            }
291        }
292
293        if s.is_empty() {
294            return Err(ParseBigIntError::empty());
295        }
296
297        if s.starts_with('_') {
298            // Must lead with a real digit!
299            return Err(ParseBigIntError::invalid());
300        }
301
302        // First normalize all characters to plain digit values
303        let mut v = Vec::with_capacity(s.len());
304        for b in s.bytes() {
305            let d = match b {
306                b'0'..=b'9' => b - b'0',
307                b'a'..=b'z' => b - b'a' + 10,
308                b'A'..=b'Z' => b - b'A' + 10,
309                b'_' => continue,
310                _ => u8::MAX,
311            };
312            if d < radix as u8 {
313                v.push(d);
314            } else {
315                return Err(ParseBigIntError::invalid());
316            }
317        }
318
319        let res = if radix.is_power_of_two() {
320            // Powers of two can use bitwise masks and shifting instead of multiplication
321            let bits = ilog2(radix);
322            v.reverse();
323            if big_digit::BITS % bits == 0 {
324                from_bitwise_digits_le(&v, bits)
325            } else {
326                from_inexact_bitwise_digits_le(&v, bits)
327            }
328        } else {
329            from_radix_digits_be(&v, radix)
330        };
331        Ok(res)
332    }
333}
334
335forward_val_val_binop!(impl BitAnd for BigUint, bitand);
336forward_ref_val_binop!(impl BitAnd for BigUint, bitand);
337
338// do not use forward_ref_ref_binop_commutative! for bitand so that we can
339// clone the smaller value rather than the larger, avoiding over-allocation
340impl<'a, 'b> BitAnd<&'b BigUint> for &'a BigUint {
341    type Output = BigUint;
342
343    #[inline]
344    fn bitand(self, other: &BigUint) -> BigUint {
345        // forward to val-ref, choosing the smaller to clone
346        if self.data.len() <= other.data.len() {
347            self.clone() & other
348        } else {
349            other.clone() & self
350        }
351    }
352}
353
354forward_val_assign!(impl BitAndAssign for BigUint, bitand_assign);
355
356impl<'a> BitAnd<&'a BigUint> for BigUint {
357    type Output = BigUint;
358
359    #[inline]
360    fn bitand(mut self, other: &BigUint) -> BigUint {
361        self &= other;
362        self
363    }
364}
365impl<'a> BitAndAssign<&'a BigUint> for BigUint {
366    #[inline]
367    fn bitand_assign(&mut self, other: &BigUint) {
368        for (ai, &bi) in self.data.iter_mut().zip(other.data.iter()) {
369            *ai &= bi;
370        }
371        self.data.truncate(other.data.len());
372        self.normalize();
373    }
374}
375
376forward_all_binop_to_val_ref_commutative!(impl BitOr for BigUint, bitor);
377forward_val_assign!(impl BitOrAssign for BigUint, bitor_assign);
378
379impl<'a> BitOr<&'a BigUint> for BigUint {
380    type Output = BigUint;
381
382    fn bitor(mut self, other: &BigUint) -> BigUint {
383        self |= other;
384        self
385    }
386}
387impl<'a> BitOrAssign<&'a BigUint> for BigUint {
388    #[inline]
389    fn bitor_assign(&mut self, other: &BigUint) {
390        for (ai, &bi) in self.data.iter_mut().zip(other.data.iter()) {
391            *ai |= bi;
392        }
393        if other.data.len() > self.data.len() {
394            let extra = &other.data[self.data.len()..];
395            self.data.extend(extra.iter().cloned());
396        }
397    }
398}
399
400forward_all_binop_to_val_ref_commutative!(impl BitXor for BigUint, bitxor);
401forward_val_assign!(impl BitXorAssign for BigUint, bitxor_assign);
402
403impl<'a> BitXor<&'a BigUint> for BigUint {
404    type Output = BigUint;
405
406    fn bitxor(mut self, other: &BigUint) -> BigUint {
407        self ^= other;
408        self
409    }
410}
411impl<'a> BitXorAssign<&'a BigUint> for BigUint {
412    #[inline]
413    fn bitxor_assign(&mut self, other: &BigUint) {
414        for (ai, &bi) in self.data.iter_mut().zip(other.data.iter()) {
415            *ai ^= bi;
416        }
417        if other.data.len() > self.data.len() {
418            let extra = &other.data[self.data.len()..];
419            self.data.extend(extra.iter().cloned());
420        }
421        self.normalize();
422    }
423}
424
425impl Shl<usize> for BigUint {
426    type Output = BigUint;
427
428    #[inline]
429    fn shl(self, rhs: usize) -> BigUint {
430        biguint_shl(Cow::Owned(self), rhs)
431    }
432}
433impl<'a> Shl<usize> for &'a BigUint {
434    type Output = BigUint;
435
436    #[inline]
437    fn shl(self, rhs: usize) -> BigUint {
438        biguint_shl(Cow::Borrowed(self), rhs)
439    }
440}
441
442impl ShlAssign<usize> for BigUint {
443    #[inline]
444    fn shl_assign(&mut self, rhs: usize) {
445        let n = mem::replace(self, BigUint::zero());
446        *self = n << rhs;
447    }
448}
449
450impl Shr<usize> for BigUint {
451    type Output = BigUint;
452
453    #[inline]
454    fn shr(self, rhs: usize) -> BigUint {
455        biguint_shr(Cow::Owned(self), rhs)
456    }
457}
458impl<'a> Shr<usize> for &'a BigUint {
459    type Output = BigUint;
460
461    #[inline]
462    fn shr(self, rhs: usize) -> BigUint {
463        biguint_shr(Cow::Borrowed(self), rhs)
464    }
465}
466
467impl ShrAssign<usize> for BigUint {
468    #[inline]
469    fn shr_assign(&mut self, rhs: usize) {
470        let n = mem::replace(self, BigUint::zero());
471        *self = n >> rhs;
472    }
473}
474
475impl Zero for BigUint {
476    #[inline]
477    fn zero() -> BigUint {
478        BigUint::new(Vec::new())
479    }
480
481    #[inline]
482    fn is_zero(&self) -> bool {
483        self.data.is_empty()
484    }
485}
486
487impl One for BigUint {
488    #[inline]
489    fn one() -> BigUint {
490        BigUint::new(vec![1])
491    }
492
493    #[inline]
494    fn is_one(&self) -> bool {
495        self.data[..] == [1]
496    }
497}
498
499impl Unsigned for BigUint {}
500
501macro_rules! pow_impl {
502    ($T:ty) => {
503        impl<'a> Pow<$T> for &'a BigUint {
504            type Output = BigUint;
505
506            #[inline]
507            fn pow(self, mut exp: $T) -> Self::Output {
508                if exp == 0 {
509                    return BigUint::one();
510                }
511                let mut base = self.clone();
512
513                while exp & 1 == 0 {
514                    base = &base * &base;
515                    exp >>= 1;
516                }
517
518                if exp == 1 {
519                    return base;
520                }
521
522                let mut acc = base.clone();
523                while exp > 1 {
524                    exp >>= 1;
525                    base = &base * &base;
526                    if exp & 1 == 1 {
527                        acc = &acc * &base;
528                    }
529                }
530                acc
531            }
532        }
533
534        impl<'a, 'b> Pow<&'b $T> for &'a BigUint {
535            type Output = BigUint;
536
537            #[inline]
538            fn pow(self, exp: &$T) -> Self::Output {
539                self.pow(*exp)
540            }
541        }
542    };
543}
544
545pow_impl!(u8);
546pow_impl!(u16);
547pow_impl!(u32);
548pow_impl!(u64);
549pow_impl!(usize);
550#[cfg(has_i128)]
551pow_impl!(u128);
552
553forward_all_binop_to_val_ref_commutative!(impl Add for BigUint, add);
554forward_val_assign!(impl AddAssign for BigUint, add_assign);
555
556impl<'a> Add<&'a BigUint> for BigUint {
557    type Output = BigUint;
558
559    fn add(mut self, other: &BigUint) -> BigUint {
560        self += other;
561        self
562    }
563}
564impl<'a> AddAssign<&'a BigUint> for BigUint {
565    #[inline]
566    fn add_assign(&mut self, other: &BigUint) {
567        let self_len = self.data.len();
568        let carry = if self_len < other.data.len() {
569            let lo_carry = __add2(&mut self.data[..], &other.data[..self_len]);
570            self.data.extend_from_slice(&other.data[self_len..]);
571            __add2(&mut self.data[self_len..], &[lo_carry])
572        } else {
573            __add2(&mut self.data[..], &other.data[..])
574        };
575        if carry != 0 {
576            self.data.push(carry);
577        }
578    }
579}
580
581promote_unsigned_scalars!(impl Add for BigUint, add);
582promote_unsigned_scalars_assign!(impl AddAssign for BigUint, add_assign);
583forward_all_scalar_binop_to_val_val_commutative!(impl Add<u32> for BigUint, add);
584forward_all_scalar_binop_to_val_val_commutative!(impl Add<u64> for BigUint, add);
585#[cfg(has_i128)]
586forward_all_scalar_binop_to_val_val_commutative!(impl Add<u128> for BigUint, add);
587
588impl Add<u32> for BigUint {
589    type Output = BigUint;
590
591    #[inline]
592    fn add(mut self, other: u32) -> BigUint {
593        self += other;
594        self
595    }
596}
597
598impl AddAssign<u32> for BigUint {
599    #[inline]
600    fn add_assign(&mut self, other: u32) {
601        if other != 0 {
602            if self.data.len() == 0 {
603                self.data.push(0);
604            }
605
606            let carry = __add2(&mut self.data, &[other as BigDigit]);
607            if carry != 0 {
608                self.data.push(carry);
609            }
610        }
611    }
612}
613
614impl Add<u64> for BigUint {
615    type Output = BigUint;
616
617    #[inline]
618    fn add(mut self, other: u64) -> BigUint {
619        self += other;
620        self
621    }
622}
623
624impl AddAssign<u64> for BigUint {
625    #[cfg(not(feature = "u64_digit"))]
626    #[inline]
627    fn add_assign(&mut self, other: u64) {
628        let (hi, lo) = big_digit::from_doublebigdigit(other);
629        if hi == 0 {
630            *self += lo;
631        } else {
632            while self.data.len() < 2 {
633                self.data.push(0);
634            }
635
636            let carry = __add2(&mut self.data, &[lo, hi]);
637            if carry != 0 {
638                self.data.push(carry);
639            }
640        }
641    }
642
643    #[cfg(feature = "u64_digit")]
644    #[inline]
645    fn add_assign(&mut self, other: u64) {
646        if other != 0 {
647            if self.data.len() == 0 {
648                self.data.push(0);
649            }
650
651            let carry = __add2(&mut self.data, &[other as BigDigit]);
652            if carry != 0 {
653                self.data.push(carry);
654            }
655        }
656    }
657}
658
659#[cfg(has_i128)]
660impl Add<u128> for BigUint {
661    type Output = BigUint;
662
663    #[inline]
664    fn add(mut self, other: u128) -> BigUint {
665        self += other;
666        self
667    }
668}
669
670#[cfg(has_i128)]
671impl AddAssign<u128> for BigUint {
672    #[cfg(not(feature = "u64_digit"))]
673    #[inline]
674    fn add_assign(&mut self, other: u128) {
675        if other <= u64::max_value() as u128 {
676            *self += other as u64
677        } else {
678            let (a, b, c, d) = u32_from_u128(other);
679            let carry = if a > 0 {
680                while self.data.len() < 4 {
681                    self.data.push(0);
682                }
683                __add2(&mut self.data, &[d, c, b, a])
684            } else {
685                debug_assert!(b > 0);
686                while self.data.len() < 3 {
687                    self.data.push(0);
688                }
689                __add2(&mut self.data, &[d, c, b])
690            };
691
692            if carry != 0 {
693                self.data.push(carry);
694            }
695        }
696    }
697
698    #[cfg(feature = "u64_digit")]
699    #[inline]
700    fn add_assign(&mut self, other: u128) {
701        let (hi, lo) = big_digit::from_doublebigdigit(other);
702        if hi == 0 {
703            *self += lo;
704        } else {
705            while self.data.len() < 2 {
706                self.data.push(0);
707            }
708
709            let carry = __add2(&mut self.data, &[lo, hi]);
710            if carry != 0 {
711                self.data.push(carry);
712            }
713        }
714    }
715}
716
717forward_val_val_binop!(impl Sub for BigUint, sub);
718forward_ref_ref_binop!(impl Sub for BigUint, sub);
719forward_val_assign!(impl SubAssign for BigUint, sub_assign);
720
721impl<'a> Sub<&'a BigUint> for BigUint {
722    type Output = BigUint;
723
724    fn sub(mut self, other: &BigUint) -> BigUint {
725        self -= other;
726        self
727    }
728}
729impl<'a> SubAssign<&'a BigUint> for BigUint {
730    fn sub_assign(&mut self, other: &'a BigUint) {
731        sub2(&mut self.data[..], &other.data[..]);
732        self.normalize();
733    }
734}
735
736impl<'a> Sub<BigUint> for &'a BigUint {
737    type Output = BigUint;
738
739    fn sub(self, mut other: BigUint) -> BigUint {
740        let other_len = other.data.len();
741        if other_len < self.data.len() {
742            let lo_borrow = __sub2rev(&self.data[..other_len], &mut other.data);
743            other.data.extend_from_slice(&self.data[other_len..]);
744            if lo_borrow != 0 {
745                sub2(&mut other.data[other_len..], &[1])
746            }
747        } else {
748            sub2rev(&self.data[..], &mut other.data[..]);
749        }
750        other.normalized()
751    }
752}
753
754promote_unsigned_scalars!(impl Sub for BigUint, sub);
755promote_unsigned_scalars_assign!(impl SubAssign for BigUint, sub_assign);
756forward_all_scalar_binop_to_val_val!(impl Sub<u32> for BigUint, sub);
757forward_all_scalar_binop_to_val_val!(impl Sub<u64> for BigUint, sub);
758#[cfg(has_i128)]
759forward_all_scalar_binop_to_val_val!(impl Sub<u128> for BigUint, sub);
760
761impl Sub<u32> for BigUint {
762    type Output = BigUint;
763
764    #[inline]
765    fn sub(mut self, other: u32) -> BigUint {
766        self -= other;
767        self
768    }
769}
770impl SubAssign<u32> for BigUint {
771    fn sub_assign(&mut self, other: u32) {
772        sub2(&mut self.data[..], &[other as BigDigit]);
773        self.normalize();
774    }
775}
776
777impl Sub<BigUint> for u32 {
778    type Output = BigUint;
779
780    #[cfg(not(feature = "u64_digit"))]
781    #[inline]
782    fn sub(self, mut other: BigUint) -> BigUint {
783        if other.data.len() == 0 {
784            other.data.push(self);
785        } else {
786            sub2rev(&[self], &mut other.data[..]);
787        }
788        other.normalized()
789    }
790
791    #[cfg(feature = "u64_digit")]
792    #[inline]
793    fn sub(self, mut other: BigUint) -> BigUint {
794        if other.data.len() == 0 {
795            other.data.push(self as BigDigit);
796        } else {
797            sub2rev(&[self as BigDigit], &mut other.data[..]);
798        }
799        other.normalized()
800    }
801}
802
803impl Sub<u64> for BigUint {
804    type Output = BigUint;
805
806    #[inline]
807    fn sub(mut self, other: u64) -> BigUint {
808        self -= other;
809        self
810    }
811}
812
813impl SubAssign<u64> for BigUint {
814    #[cfg(not(feature = "u64_digit"))]
815    #[inline]
816    fn sub_assign(&mut self, other: u64) {
817        let (hi, lo) = big_digit::from_doublebigdigit(other);
818        sub2(&mut self.data[..], &[lo, hi]);
819        self.normalize();
820    }
821
822    #[cfg(feature = "u64_digit")]
823    #[inline]
824    fn sub_assign(&mut self, other: u64) {
825        sub2(&mut self.data[..], &[other as BigDigit]);
826        self.normalize();
827    }
828}
829
830impl Sub<BigUint> for u64 {
831    type Output = BigUint;
832
833    #[cfg(not(feature = "u64_digit"))]
834    #[inline]
835    fn sub(self, mut other: BigUint) -> BigUint {
836        while other.data.len() < 2 {
837            other.data.push(0);
838        }
839
840        let (hi, lo) = big_digit::from_doublebigdigit(self);
841        sub2rev(&[lo, hi], &mut other.data[..]);
842        other.normalized()
843    }
844
845    #[cfg(feature = "u64_digit")]
846    #[inline]
847    fn sub(self, mut other: BigUint) -> BigUint {
848        if other.data.len() == 0 {
849            other.data.push(self);
850        } else {
851            sub2rev(&[self], &mut other.data[..]);
852        }
853        other.normalized()
854    }
855}
856
857#[cfg(has_i128)]
858impl Sub<u128> for BigUint {
859    type Output = BigUint;
860
861    #[inline]
862    fn sub(mut self, other: u128) -> BigUint {
863        self -= other;
864        self
865    }
866}
867#[cfg(has_i128)]
868impl SubAssign<u128> for BigUint {
869    #[cfg(not(feature = "u64_digit"))]
870    #[inline]
871    fn sub_assign(&mut self, other: u128) {
872        let (a, b, c, d) = u32_from_u128(other);
873        sub2(&mut self.data[..], &[d, c, b, a]);
874        self.normalize();
875    }
876
877    #[cfg(feature = "u64_digit")]
878    #[inline]
879    fn sub_assign(&mut self, other: u128) {
880        let (hi, lo) = big_digit::from_doublebigdigit(other);
881        sub2(&mut self.data[..], &[lo, hi]);
882        self.normalize();
883    }
884}
885
886#[cfg(has_i128)]
887impl Sub<BigUint> for u128 {
888    type Output = BigUint;
889
890    #[cfg(not(feature = "u64_digit"))]
891    #[inline]
892    fn sub(self, mut other: BigUint) -> BigUint {
893        while other.data.len() < 4 {
894            other.data.push(0);
895        }
896
897        let (a, b, c, d) = u32_from_u128(self);
898        sub2rev(&[d, c, b, a], &mut other.data[..]);
899        other.normalized()
900    }
901
902    #[cfg(feature = "u64_digit")]
903    #[inline]
904    fn sub(self, mut other: BigUint) -> BigUint {
905        while other.data.len() < 2 {
906            other.data.push(0);
907        }
908
909        let (hi, lo) = big_digit::from_doublebigdigit(self);
910        sub2rev(&[lo, hi], &mut other.data[..]);
911        other.normalized()
912    }
913}
914
915forward_all_binop_to_ref_ref!(impl Mul for BigUint, mul);
916forward_val_assign!(impl MulAssign for BigUint, mul_assign);
917
918impl<'a, 'b> Mul<&'b BigUint> for &'a BigUint {
919    type Output = BigUint;
920
921    #[inline]
922    fn mul(self, other: &BigUint) -> BigUint {
923        mul3(&self.data[..], &other.data[..])
924    }
925}
926
927impl<'a, 'b> Mul<&'a BigInt> for &'b BigUint {
928    type Output = BigInt;
929
930    #[inline]
931    fn mul(self, other: &BigInt) -> BigInt {
932        BigInt {
933            data: mul3(&self.data[..], &other.digits()[..]),
934            sign: other.sign,
935        }
936    }
937}
938
939impl<'a> MulAssign<&'a BigUint> for BigUint {
940    #[inline]
941    fn mul_assign(&mut self, other: &'a BigUint) {
942        *self = &*self * other
943    }
944}
945
946promote_unsigned_scalars!(impl Mul for BigUint, mul);
947promote_unsigned_scalars_assign!(impl MulAssign for BigUint, mul_assign);
948forward_all_scalar_binop_to_val_val_commutative!(impl Mul<u32> for BigUint, mul);
949forward_all_scalar_binop_to_val_val_commutative!(impl Mul<u64> for BigUint, mul);
950#[cfg(has_i128)]
951forward_all_scalar_binop_to_val_val_commutative!(impl Mul<u128> for BigUint, mul);
952
953impl Mul<u32> for BigUint {
954    type Output = BigUint;
955
956    #[inline]
957    fn mul(mut self, other: u32) -> BigUint {
958        self *= other;
959        self
960    }
961}
962impl MulAssign<u32> for BigUint {
963    #[inline]
964    fn mul_assign(&mut self, other: u32) {
965        if other == 0 {
966            self.data.clear();
967        } else {
968            let carry = scalar_mul(&mut self.data[..], other as BigDigit);
969            if carry != 0 {
970                self.data.push(carry);
971            }
972        }
973    }
974}
975
976impl Mul<u64> for BigUint {
977    type Output = BigUint;
978
979    #[inline]
980    fn mul(mut self, other: u64) -> BigUint {
981        self *= other;
982        self
983    }
984}
985impl MulAssign<u64> for BigUint {
986    #[cfg(not(feature = "u64_digit"))]
987    #[inline]
988    fn mul_assign(&mut self, other: u64) {
989        if other == 0 {
990            self.data.clear();
991        } else if other <= BigDigit::max_value() as u64 {
992            *self *= other as BigDigit
993        } else {
994            let (hi, lo) = big_digit::from_doublebigdigit(other);
995            *self = mul3(&self.data[..], &[lo, hi])
996        }
997    }
998
999    #[cfg(feature = "u64_digit")]
1000    #[inline]
1001    fn mul_assign(&mut self, other: u64) {
1002        if other == 0 {
1003            self.data.clear();
1004        } else {
1005            let carry = scalar_mul(&mut self.data[..], other as BigDigit);
1006            if carry != 0 {
1007                self.data.push(carry);
1008            }
1009        }
1010    }
1011}
1012
1013#[cfg(has_i128)]
1014impl Mul<u128> for BigUint {
1015    type Output = BigUint;
1016
1017    #[inline]
1018    fn mul(mut self, other: u128) -> BigUint {
1019        self *= other;
1020        self
1021    }
1022}
1023#[cfg(has_i128)]
1024impl MulAssign<u128> for BigUint {
1025    #[cfg(not(feature = "u64_digit"))]
1026    #[inline]
1027    fn mul_assign(&mut self, other: u128) {
1028        if other == 0 {
1029            self.data.clear();
1030        } else if other <= BigDigit::max_value() as u128 {
1031            *self *= other as BigDigit
1032        } else {
1033            let (a, b, c, d) = u32_from_u128(other);
1034            *self = mul3(&self.data[..], &[d, c, b, a])
1035        }
1036    }
1037
1038    #[cfg(feature = "u64_digit")]
1039    #[inline]
1040    fn mul_assign(&mut self, other: u128) {
1041        if other == 0 {
1042            self.data.clear();
1043        } else if other <= BigDigit::max_value() as u128 {
1044            *self *= other as BigDigit
1045        } else {
1046            let (hi, lo) = big_digit::from_doublebigdigit(other);
1047            *self = mul3(&self.data[..], &[lo, hi])
1048        }
1049    }
1050}
1051
1052forward_all_binop_to_ref_ref!(impl Div for BigUint, div);
1053forward_val_assign!(impl DivAssign for BigUint, div_assign);
1054
1055impl<'a, 'b> Div<&'b BigUint> for &'a BigUint {
1056    type Output = BigUint;
1057
1058    #[inline]
1059    fn div(self, other: &BigUint) -> BigUint {
1060        let (q, _) = self.div_rem(other);
1061        q
1062    }
1063}
1064impl<'a> DivAssign<&'a BigUint> for BigUint {
1065    #[inline]
1066    fn div_assign(&mut self, other: &'a BigUint) {
1067        *self = &*self / other;
1068    }
1069}
1070
1071promote_unsigned_scalars!(impl Div for BigUint, div);
1072promote_unsigned_scalars_assign!(impl DivAssign for BigUint, div_assign);
1073forward_all_scalar_binop_to_val_val!(impl Div<u32> for BigUint, div);
1074forward_all_scalar_binop_to_val_val!(impl Div<u64> for BigUint, div);
1075#[cfg(has_i128)]
1076forward_all_scalar_binop_to_val_val!(impl Div<u128> for BigUint, div);
1077
1078impl Div<u32> for BigUint {
1079    type Output = BigUint;
1080
1081    #[inline]
1082    fn div(self, other: u32) -> BigUint {
1083        let (q, _) = div_rem_digit(self, other as BigDigit);
1084        q
1085    }
1086}
1087impl DivAssign<u32> for BigUint {
1088    #[inline]
1089    fn div_assign(&mut self, other: u32) {
1090        *self = &*self / other;
1091    }
1092}
1093
1094impl Div<BigUint> for u32 {
1095    type Output = BigUint;
1096
1097    #[inline]
1098    fn div(self, other: BigUint) -> BigUint {
1099        match other.data.len() {
1100            0 => panic!(),
1101            1 => From::from(self as BigDigit / other.data[0]),
1102            _ => Zero::zero(),
1103        }
1104    }
1105}
1106
1107impl Div<u64> for BigUint {
1108    type Output = BigUint;
1109
1110    #[inline]
1111    fn div(self, other: u64) -> BigUint {
1112        let (q, _) = self.div_rem(&From::from(other));
1113        q
1114    }
1115}
1116impl DivAssign<u64> for BigUint {
1117    #[inline]
1118    fn div_assign(&mut self, other: u64) {
1119        *self = &*self / other;
1120    }
1121}
1122
1123impl Div<BigUint> for u64 {
1124    type Output = BigUint;
1125
1126    #[cfg(not(feature = "u64_digit"))]
1127    #[inline]
1128    fn div(self, other: BigUint) -> BigUint {
1129        match other.data.len() {
1130            0 => panic!(),
1131            1 => From::from(self / other.data[0] as u64),
1132            2 => From::from(self / big_digit::to_doublebigdigit(other.data[1], other.data[0])),
1133            _ => Zero::zero(),
1134        }
1135    }
1136
1137    #[cfg(feature = "u64_digit")]
1138    #[inline]
1139    fn div(self, other: BigUint) -> BigUint {
1140        match other.data.len() {
1141            0 => panic!(),
1142            1 => From::from(self / other.data[0]),
1143            _ => Zero::zero(),
1144        }
1145    }
1146}
1147
1148#[cfg(has_i128)]
1149impl Div<u128> for BigUint {
1150    type Output = BigUint;
1151
1152    #[inline]
1153    fn div(self, other: u128) -> BigUint {
1154        let (q, _) = self.div_rem(&From::from(other));
1155        q
1156    }
1157}
1158
1159#[cfg(has_i128)]
1160impl DivAssign<u128> for BigUint {
1161    #[inline]
1162    fn div_assign(&mut self, other: u128) {
1163        *self = &*self / other;
1164    }
1165}
1166
1167#[cfg(has_i128)]
1168impl Div<BigUint> for u128 {
1169    type Output = BigUint;
1170
1171    #[cfg(not(feature = "u64_digit"))]
1172    #[inline]
1173    fn div(self, other: BigUint) -> BigUint {
1174        match other.data.len() {
1175            0 => panic!(),
1176            1 => From::from(self / other.data[0] as u128),
1177            2 => From::from(
1178                self / big_digit::to_doublebigdigit(other.data[1], other.data[0]) as u128,
1179            ),
1180            3 => From::from(self / u32_to_u128(0, other.data[2], other.data[1], other.data[0])),
1181            4 => From::from(
1182                self / u32_to_u128(other.data[3], other.data[2], other.data[1], other.data[0]),
1183            ),
1184            _ => Zero::zero(),
1185        }
1186    }
1187
1188    #[cfg(feature = "u64_digit")]
1189    #[inline]
1190    fn div(self, other: BigUint) -> BigUint {
1191        match other.data.len() {
1192            0 => panic!(),
1193            1 => From::from(self / other.data[0] as u128),
1194            2 => From::from(self / big_digit::to_doublebigdigit(other.data[1], other.data[0])),
1195            _ => Zero::zero(),
1196        }
1197    }
1198}
1199
1200forward_all_binop_to_ref_ref!(impl Rem for BigUint, rem);
1201forward_val_assign!(impl RemAssign for BigUint, rem_assign);
1202
1203impl<'a, 'b> Rem<&'b BigUint> for &'a BigUint {
1204    type Output = BigUint;
1205
1206    #[inline]
1207    fn rem(self, other: &BigUint) -> BigUint {
1208        let (_, r) = self.div_rem(other);
1209        r
1210    }
1211}
1212impl<'a> RemAssign<&'a BigUint> for BigUint {
1213    #[inline]
1214    fn rem_assign(&mut self, other: &BigUint) {
1215        *self = &*self % other;
1216    }
1217}
1218
1219promote_unsigned_scalars!(impl Rem for BigUint, rem);
1220promote_unsigned_scalars_assign!(impl RemAssign for BigUint, rem_assign);
1221forward_all_scalar_binop_to_val_val!(impl Rem<u32> for BigUint, rem);
1222forward_all_scalar_binop_to_val_val!(impl Rem<u64> for BigUint, rem);
1223#[cfg(has_i128)]
1224forward_all_scalar_binop_to_val_val!(impl Rem<u128> for BigUint, rem);
1225
1226impl Rem<u32> for BigUint {
1227    type Output = BigUint;
1228
1229    #[inline]
1230    fn rem(self, other: u32) -> BigUint {
1231        let (_, r) = div_rem_digit(self, other as BigDigit);
1232        From::from(r)
1233    }
1234}
1235impl RemAssign<u32> for BigUint {
1236    #[inline]
1237    fn rem_assign(&mut self, other: u32) {
1238        *self = &*self % other;
1239    }
1240}
1241
1242impl Rem<BigUint> for u32 {
1243    type Output = BigUint;
1244
1245    #[inline]
1246    fn rem(mut self, other: BigUint) -> BigUint {
1247        self %= other;
1248        From::from(self)
1249    }
1250}
1251
1252macro_rules! impl_rem_assign_scalar {
1253    ($scalar:ty, $to_scalar:ident) => {
1254        forward_val_assign_scalar!(impl RemAssign for BigUint, $scalar, rem_assign);
1255        impl<'a> RemAssign<&'a BigUint> for $scalar {
1256            #[inline]
1257            fn rem_assign(&mut self, other: &BigUint) {
1258                *self = match other.$to_scalar() {
1259                    None => *self,
1260                    Some(0) => panic!(),
1261                    Some(v) => *self % v
1262                };
1263            }
1264        }
1265    }
1266}
1267// we can scalar %= BigUint for any scalar, including signed types
1268#[cfg(has_i128)]
1269impl_rem_assign_scalar!(u128, to_u128);
1270impl_rem_assign_scalar!(usize, to_usize);
1271impl_rem_assign_scalar!(u64, to_u64);
1272impl_rem_assign_scalar!(u32, to_u32);
1273impl_rem_assign_scalar!(u16, to_u16);
1274impl_rem_assign_scalar!(u8, to_u8);
1275#[cfg(has_i128)]
1276impl_rem_assign_scalar!(i128, to_i128);
1277impl_rem_assign_scalar!(isize, to_isize);
1278impl_rem_assign_scalar!(i64, to_i64);
1279impl_rem_assign_scalar!(i32, to_i32);
1280impl_rem_assign_scalar!(i16, to_i16);
1281impl_rem_assign_scalar!(i8, to_i8);
1282
1283impl Rem<u64> for BigUint {
1284    type Output = BigUint;
1285
1286    #[inline]
1287    fn rem(self, other: u64) -> BigUint {
1288        let (_, r) = self.div_rem(&From::from(other));
1289        r
1290    }
1291}
1292impl RemAssign<u64> for BigUint {
1293    #[inline]
1294    fn rem_assign(&mut self, other: u64) {
1295        *self = &*self % other;
1296    }
1297}
1298
1299impl Rem<BigUint> for u64 {
1300    type Output = BigUint;
1301
1302    #[inline]
1303    fn rem(mut self, other: BigUint) -> BigUint {
1304        self %= other;
1305        From::from(self)
1306    }
1307}
1308
1309#[cfg(has_i128)]
1310impl Rem<u128> for BigUint {
1311    type Output = BigUint;
1312
1313    #[inline]
1314    fn rem(self, other: u128) -> BigUint {
1315        let (_, r) = self.div_rem(&From::from(other));
1316        r
1317    }
1318}
1319#[cfg(has_i128)]
1320impl RemAssign<u128> for BigUint {
1321    #[inline]
1322    fn rem_assign(&mut self, other: u128) {
1323        *self = &*self % other;
1324    }
1325}
1326
1327#[cfg(has_i128)]
1328impl Rem<BigUint> for u128 {
1329    type Output = BigUint;
1330
1331    #[inline]
1332    fn rem(mut self, other: BigUint) -> BigUint {
1333        self %= other;
1334        From::from(self)
1335    }
1336}
1337
1338impl Neg for BigUint {
1339    type Output = BigUint;
1340
1341    #[inline]
1342    fn neg(self) -> BigUint {
1343        panic!()
1344    }
1345}
1346
1347impl<'a> Neg for &'a BigUint {
1348    type Output = BigUint;
1349
1350    #[inline]
1351    fn neg(self) -> BigUint {
1352        panic!()
1353    }
1354}
1355
1356impl CheckedAdd for BigUint {
1357    #[inline]
1358    fn checked_add(&self, v: &BigUint) -> Option<BigUint> {
1359        Some(self.add(v))
1360    }
1361}
1362
1363impl CheckedSub for BigUint {
1364    #[inline]
1365    fn checked_sub(&self, v: &BigUint) -> Option<BigUint> {
1366        match self.cmp(v) {
1367            Less => None,
1368            Equal => Some(Zero::zero()),
1369            Greater => Some(self.sub(v)),
1370        }
1371    }
1372}
1373
1374impl CheckedMul for BigUint {
1375    #[inline]
1376    fn checked_mul(&self, v: &BigUint) -> Option<BigUint> {
1377        Some(self.mul(v))
1378    }
1379}
1380
1381impl CheckedDiv for BigUint {
1382    #[inline]
1383    fn checked_div(&self, v: &BigUint) -> Option<BigUint> {
1384        if v.is_zero() {
1385            None
1386        } else {
1387            Some(self.div(v))
1388        }
1389    }
1390}
1391
1392impl Integer for BigUint {
1393    #[inline]
1394    fn div_rem(&self, other: &BigUint) -> (BigUint, BigUint) {
1395        div_rem(self, other)
1396    }
1397
1398    #[inline]
1399    fn div_floor(&self, other: &BigUint) -> BigUint {
1400        let (d, _) = div_rem(self, other);
1401        d
1402    }
1403
1404    #[inline]
1405    fn mod_floor(&self, other: &BigUint) -> BigUint {
1406        let (_, m) = div_rem(self, other);
1407        m
1408    }
1409
1410    #[inline]
1411    fn div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint) {
1412        div_rem(self, other)
1413    }
1414
1415    /// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
1416    ///
1417    /// The result is always positive.
1418    #[inline]
1419    fn gcd(&self, other: &Self) -> Self {
1420        let (res, _, _) = extended_gcd(Cow::Borrowed(self), Cow::Borrowed(other), false);
1421        res.into_biguint().unwrap()
1422    }
1423
1424    /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
1425    #[inline]
1426    fn lcm(&self, other: &BigUint) -> BigUint {
1427        self / self.gcd(other) * other
1428    }
1429
1430    /// Deprecated, use `is_multiple_of` instead.
1431    #[inline]
1432    fn divides(&self, other: &BigUint) -> bool {
1433        self.is_multiple_of(other)
1434    }
1435
1436    /// Returns `true` if the number is a multiple of `other`.
1437    #[inline]
1438    fn is_multiple_of(&self, other: &BigUint) -> bool {
1439        (self % other).is_zero()
1440    }
1441
1442    /// Returns `true` if the number is divisible by `2`.
1443    #[inline]
1444    fn is_even(&self) -> bool {
1445        // Considering only the last digit.
1446        match self.data.first() {
1447            Some(x) => x.is_even(),
1448            None => true,
1449        }
1450    }
1451
1452    /// Returns `true` if the number is not divisible by `2`.
1453    #[inline]
1454    fn is_odd(&self) -> bool {
1455        !self.is_even()
1456    }
1457}
1458
1459#[inline]
1460fn fixpoint<F>(mut x: BigUint, max_bits: usize, f: F) -> BigUint
1461where
1462    F: Fn(&BigUint) -> BigUint,
1463{
1464    let mut xn = f(&x);
1465
1466    // If the value increased, then the initial guess must have been low.
1467    // Repeat until we reverse course.
1468    while x < xn {
1469        // Sometimes an increase will go way too far, especially with large
1470        // powers, and then take a long time to walk back.  We know an upper
1471        // bound based on bit size, so saturate on that.
1472        x = if xn.bits() > max_bits {
1473            BigUint::one() << max_bits
1474        } else {
1475            xn
1476        };
1477        xn = f(&x);
1478    }
1479
1480    // Now keep repeating while the estimate is decreasing.
1481    while x > xn {
1482        x = xn;
1483        xn = f(&x);
1484    }
1485    x
1486}
1487
1488impl Roots for BigUint {
1489    // nth_root, sqrt and cbrt use Newton's method to compute
1490    // principal root of a given degree for a given integer.
1491
1492    // Reference:
1493    // Brent & Zimmermann, Modern Computer Arithmetic, v0.5.9, Algorithm 1.14
1494    fn nth_root(&self, n: u32) -> Self {
1495        assert!(n > 0, "root degree n must be at least 1");
1496
1497        if self.is_zero() || self.is_one() {
1498            return self.clone();
1499        }
1500
1501        match n {
1502            // Optimize for small n
1503            1 => return self.clone(),
1504            2 => return self.sqrt(),
1505            3 => return self.cbrt(),
1506            _ => (),
1507        }
1508
1509        // The root of non-zero values less than 2ⁿ can only be 1.
1510        let bits = self.bits();
1511        if bits <= n as usize {
1512            return BigUint::one();
1513        }
1514
1515        // If we fit in `u64`, compute the root that way.
1516        if let Some(x) = self.to_u64() {
1517            return x.nth_root(n).into();
1518        }
1519
1520        let max_bits = bits / n as usize + 1;
1521
1522        let guess = if let Some(f) = self.to_f64() {
1523            // We fit in `f64` (lossy), so get a better initial guess from that.
1524            BigUint::from_f64(exp(ln(f) / f64::from(n))).unwrap()
1525        } else {
1526            // Try to guess by scaling down such that it does fit in `f64`.
1527            // With some (x * 2ⁿᵏ), its nth root ≈ (ⁿ√x * 2ᵏ)
1528            let nsz = n as usize;
1529            let extra_bits = bits - (f64::MAX_EXP as usize - 1);
1530            let root_scale = (extra_bits + (nsz - 1)) / nsz;
1531            let scale = root_scale * nsz;
1532            if scale < bits && bits - scale > nsz {
1533                (self >> scale).nth_root(n) << root_scale
1534            } else {
1535                BigUint::one() << max_bits
1536            }
1537        };
1538
1539        let n_min_1 = n - 1;
1540        fixpoint(guess, max_bits, move |s| {
1541            let q = self / s.pow(n_min_1);
1542            let t = n_min_1 * s + q;
1543            t / n
1544        })
1545    }
1546
1547    // Reference:
1548    // Brent & Zimmermann, Modern Computer Arithmetic, v0.5.9, Algorithm 1.13
1549    fn sqrt(&self) -> Self {
1550        if self.is_zero() || self.is_one() {
1551            return self.clone();
1552        }
1553
1554        // If we fit in `u64`, compute the root that way.
1555        if let Some(x) = self.to_u64() {
1556            return x.sqrt().into();
1557        }
1558
1559        let bits = self.bits();
1560        let max_bits = bits / 2 as usize + 1;
1561
1562        let guess = if let Some(f) = self.to_f64() {
1563            // We fit in `f64` (lossy), so get a better initial guess from that.
1564            BigUint::from_f64(sqrt(f)).unwrap()
1565        } else {
1566            // Try to guess by scaling down such that it does fit in `f64`.
1567            // With some (x * 2²ᵏ), its sqrt ≈ (√x * 2ᵏ)
1568            let extra_bits = bits - (f64::MAX_EXP as usize - 1);
1569            let root_scale = (extra_bits + 1) / 2;
1570            let scale = root_scale * 2;
1571            (self >> scale).sqrt() << root_scale
1572        };
1573
1574        fixpoint(guess, max_bits, move |s| {
1575            let q = self / s;
1576            let t = s + q;
1577            t >> 1
1578        })
1579    }
1580
1581    fn cbrt(&self) -> Self {
1582        if self.is_zero() || self.is_one() {
1583            return self.clone();
1584        }
1585
1586        // If we fit in `u64`, compute the root that way.
1587        if let Some(x) = self.to_u64() {
1588            return x.cbrt().into();
1589        }
1590
1591        let bits = self.bits();
1592        let max_bits = bits / 3 as usize + 1;
1593
1594        let guess = if let Some(f) = self.to_f64() {
1595            // We fit in `f64` (lossy), so get a better initial guess from that.
1596            BigUint::from_f64(cbrt(f)).unwrap()
1597        } else {
1598            // Try to guess by scaling down such that it does fit in `f64`.
1599            // With some (x * 2³ᵏ), its cbrt ≈ (∛x * 2ᵏ)
1600            let extra_bits = bits - (f64::MAX_EXP as usize - 1);
1601            let root_scale = (extra_bits + 2) / 3;
1602            let scale = root_scale * 3;
1603            (self >> scale).cbrt() << root_scale
1604        };
1605
1606        fixpoint(guess, max_bits, move |s| {
1607            let q = self / (s * s);
1608            let t = (s << 1) + q;
1609            t / 3u32
1610        })
1611    }
1612}
1613
1614fn high_bits_to_u64(v: &BigUint) -> u64 {
1615    match v.data.len() {
1616        0 => 0,
1617        1 => v.data[0] as u64,
1618        _ => {
1619            let mut bits = v.bits();
1620            let mut ret = 0u64;
1621            let mut ret_bits = 0;
1622
1623            for d in v.data.iter().rev() {
1624                let digit_bits = (bits - 1) % big_digit::BITS + 1;
1625                let bits_want = cmp::min(64 - ret_bits, digit_bits);
1626
1627                if bits_want != 64 {
1628                    ret <<= bits_want;
1629                }
1630                ret |= *d as u64 >> (digit_bits - bits_want);
1631                ret_bits += bits_want;
1632                bits -= bits_want;
1633
1634                if ret_bits == 64 {
1635                    break;
1636                }
1637            }
1638
1639            ret
1640        }
1641    }
1642}
1643
1644impl ToPrimitive for BigUint {
1645    #[inline]
1646    fn to_i64(&self) -> Option<i64> {
1647        self.to_u64().as_ref().and_then(u64::to_i64)
1648    }
1649
1650    #[inline]
1651    #[cfg(has_i128)]
1652    fn to_i128(&self) -> Option<i128> {
1653        self.to_u128().as_ref().and_then(u128::to_i128)
1654    }
1655
1656    #[inline]
1657    fn to_u64(&self) -> Option<u64> {
1658        let mut ret: u64 = 0;
1659        let mut bits = 0;
1660
1661        for i in self.data.iter() {
1662            if bits >= 64 {
1663                return None;
1664            }
1665
1666            ret += (*i as u64) << bits;
1667            bits += big_digit::BITS;
1668        }
1669
1670        Some(ret)
1671    }
1672
1673    #[inline]
1674    #[cfg(has_i128)]
1675    fn to_u128(&self) -> Option<u128> {
1676        let mut ret: u128 = 0;
1677        let mut bits = 0;
1678
1679        for i in self.data.iter() {
1680            if bits >= 128 {
1681                return None;
1682            }
1683
1684            ret |= (*i as u128) << bits;
1685            bits += big_digit::BITS;
1686        }
1687
1688        Some(ret)
1689    }
1690
1691    #[inline]
1692    fn to_f32(&self) -> Option<f32> {
1693        let mantissa = high_bits_to_u64(self);
1694        let exponent = self.bits() - fls(mantissa);
1695
1696        if exponent > f32::MAX_EXP as usize {
1697            None
1698        } else {
1699            let ret = (mantissa as f32) * 2.0f32.powi(exponent as i32);
1700            if ret.is_infinite() {
1701                None
1702            } else {
1703                Some(ret)
1704            }
1705        }
1706    }
1707
1708    #[inline]
1709    fn to_f64(&self) -> Option<f64> {
1710        let mantissa = high_bits_to_u64(self);
1711        let exponent = self.bits() - fls(mantissa);
1712
1713        if exponent > f64::MAX_EXP as usize {
1714            None
1715        } else {
1716            let ret = (mantissa as f64) * 2.0f64.powi(exponent as i32);
1717            if ret.is_infinite() {
1718                None
1719            } else {
1720                Some(ret)
1721            }
1722        }
1723    }
1724}
1725
1726impl FromPrimitive for BigUint {
1727    #[inline]
1728    fn from_i64(n: i64) -> Option<BigUint> {
1729        if n >= 0 {
1730            Some(BigUint::from(n as u64))
1731        } else {
1732            None
1733        }
1734    }
1735
1736    #[inline]
1737    #[cfg(has_i128)]
1738    fn from_i128(n: i128) -> Option<BigUint> {
1739        if n >= 0 {
1740            Some(BigUint::from(n as u128))
1741        } else {
1742            None
1743        }
1744    }
1745
1746    #[inline]
1747    fn from_u64(n: u64) -> Option<BigUint> {
1748        Some(BigUint::from(n))
1749    }
1750
1751    #[inline]
1752    #[cfg(has_i128)]
1753    fn from_u128(n: u128) -> Option<BigUint> {
1754        Some(BigUint::from(n))
1755    }
1756
1757    #[inline]
1758    fn from_f64(mut n: f64) -> Option<BigUint> {
1759        // handle NAN, INFINITY, NEG_INFINITY
1760        if !n.is_finite() {
1761            return None;
1762        }
1763
1764        // match the rounding of casting from float to int
1765        n = FloatCore::trunc(n);
1766
1767        // handle 0.x, -0.x
1768        if n.is_zero() {
1769            return Some(BigUint::zero());
1770        }
1771
1772        let (mantissa, exponent, sign) = FloatCore::integer_decode(n);
1773
1774        if sign == -1 {
1775            return None;
1776        }
1777
1778        let mut ret = BigUint::from(mantissa);
1779        if exponent > 0 {
1780            ret = ret << exponent as usize;
1781        } else if exponent < 0 {
1782            ret = ret >> (-exponent) as usize;
1783        }
1784        Some(ret)
1785    }
1786}
1787
1788#[cfg(not(feature = "u64_digit"))]
1789impl From<u64> for BigUint {
1790    #[inline]
1791    fn from(mut n: u64) -> Self {
1792        let mut ret: BigUint = Zero::zero();
1793
1794        while n != 0 {
1795            ret.data.push(n as BigDigit);
1796            // don't overflow if BITS is 64:
1797            n = (n >> 1) >> (big_digit::BITS - 1);
1798        }
1799
1800        ret
1801    }
1802}
1803
1804#[cfg(feature = "u64_digit")]
1805impl From<u64> for BigUint {
1806    #[inline]
1807    fn from(n: u64) -> Self {
1808        BigUint::new_native(smallvec![n])
1809    }
1810}
1811
1812#[cfg(has_i128)]
1813impl From<u128> for BigUint {
1814    #[inline]
1815    fn from(mut n: u128) -> Self {
1816        let mut ret: BigUint = Zero::zero();
1817
1818        while n != 0 {
1819            ret.data.push(n as BigDigit);
1820            n >>= big_digit::BITS;
1821        }
1822
1823        ret
1824    }
1825}
1826
1827macro_rules! impl_biguint_from_uint {
1828    ($T:ty) => {
1829        impl From<$T> for BigUint {
1830            #[inline]
1831            fn from(n: $T) -> Self {
1832                BigUint::from(n as u64)
1833            }
1834        }
1835    };
1836}
1837
1838impl_biguint_from_uint!(u8);
1839impl_biguint_from_uint!(u16);
1840impl_biguint_from_uint!(u32);
1841impl_biguint_from_uint!(usize);
1842
1843/// A generic trait for converting a value to a `BigUint`.
1844pub trait ToBigUint {
1845    /// Converts the value of `self` to a `BigUint`.
1846    fn to_biguint(&self) -> Option<BigUint>;
1847}
1848
1849impl ToBigUint for BigUint {
1850    #[inline]
1851    fn to_biguint(&self) -> Option<BigUint> {
1852        Some(self.clone())
1853    }
1854}
1855
1856/// A generic trait for converting a value to a `BigUint`, and consuming the value.
1857pub trait IntoBigUint {
1858    /// Converts the value of `self` to a `BigUint`.
1859    fn into_biguint(self) -> Option<BigUint>;
1860}
1861
1862impl IntoBigUint for BigUint {
1863    #[inline]
1864    fn into_biguint(self) -> Option<BigUint> {
1865        Some(self)
1866    }
1867}
1868
1869macro_rules! impl_to_biguint {
1870    ($T:ty, $from_ty:path) => {
1871        impl ToBigUint for $T {
1872            #[inline]
1873            fn to_biguint(&self) -> Option<BigUint> {
1874                $from_ty(*self)
1875            }
1876        }
1877
1878        impl IntoBigUint for $T {
1879            #[inline]
1880            fn into_biguint(self) -> Option<BigUint> {
1881                $from_ty(self)
1882            }
1883        }
1884    };
1885}
1886
1887impl_to_biguint!(isize, FromPrimitive::from_isize);
1888impl_to_biguint!(i8, FromPrimitive::from_i8);
1889impl_to_biguint!(i16, FromPrimitive::from_i16);
1890impl_to_biguint!(i32, FromPrimitive::from_i32);
1891impl_to_biguint!(i64, FromPrimitive::from_i64);
1892#[cfg(has_i128)]
1893impl_to_biguint!(i128, FromPrimitive::from_i128);
1894
1895impl_to_biguint!(usize, FromPrimitive::from_usize);
1896impl_to_biguint!(u8, FromPrimitive::from_u8);
1897impl_to_biguint!(u16, FromPrimitive::from_u16);
1898impl_to_biguint!(u32, FromPrimitive::from_u32);
1899impl_to_biguint!(u64, FromPrimitive::from_u64);
1900#[cfg(has_i128)]
1901impl_to_biguint!(u128, FromPrimitive::from_u128);
1902
1903impl_to_biguint!(f32, FromPrimitive::from_f32);
1904impl_to_biguint!(f64, FromPrimitive::from_f64);
1905
1906// Extract bitwise digits that evenly divide BigDigit
1907fn to_bitwise_digits_le(u: &BigUint, bits: usize) -> Vec<u8> {
1908    debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits == 0);
1909
1910    let last_i = u.data.len() - 1;
1911    let mask: BigDigit = (1 << bits) - 1;
1912    let digits_per_big_digit = big_digit::BITS / bits;
1913    let digits = (u.bits() + bits - 1) / bits;
1914    let mut res = Vec::with_capacity(digits);
1915
1916    for mut r in u.data[..last_i].iter().cloned() {
1917        for _ in 0..digits_per_big_digit {
1918            res.push((r & mask) as u8);
1919            r >>= bits;
1920        }
1921    }
1922
1923    let mut r = u.data[last_i];
1924    while r != 0 {
1925        res.push((r & mask) as u8);
1926        r >>= bits;
1927    }
1928
1929    res
1930}
1931
1932// Extract bitwise digits that don't evenly divide BigDigit
1933fn to_inexact_bitwise_digits_le(u: &BigUint, bits: usize) -> Vec<u8> {
1934    debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits != 0);
1935
1936    let mask: BigDigit = (1 << bits) - 1;
1937    let digits = (u.bits() + bits - 1) / bits;
1938    let mut res = Vec::with_capacity(digits);
1939
1940    let mut r = 0;
1941    let mut rbits = 0;
1942
1943    for c in &u.data {
1944        r |= *c << rbits;
1945        rbits += big_digit::BITS;
1946
1947        while rbits >= bits {
1948            res.push((r & mask) as u8);
1949            r >>= bits;
1950
1951            // r had more bits than it could fit - grab the bits we lost
1952            if rbits > big_digit::BITS {
1953                r = *c >> (big_digit::BITS - (rbits - bits));
1954            }
1955
1956            rbits -= bits;
1957        }
1958    }
1959
1960    if rbits != 0 {
1961        res.push(r as u8);
1962    }
1963
1964    while let Some(&0) = res.last() {
1965        res.pop();
1966    }
1967
1968    res
1969}
1970
1971// Extract little-endian radix digits
1972#[inline(always)] // forced inline to get const-prop for radix=10
1973fn to_radix_digits_le(u: &BigUint, radix: u32) -> Vec<u8> {
1974    debug_assert!(!u.is_zero() && !radix.is_power_of_two());
1975
1976    // Estimate how big the result will be, so we can pre-allocate it.
1977    let bits = ilog2(radix);
1978    let radix_digits = idiv_ceil(u.bits(), bits);
1979    let mut res = Vec::with_capacity(radix_digits as usize);
1980    let mut digits = u.clone();
1981
1982    let (base, power) = get_radix_base(radix);
1983    let radix = radix as BigDigit;
1984
1985    while digits.data.len() > 1 {
1986        let (q, mut r) = div_rem_digit(digits, base);
1987        for _ in 0..power {
1988            res.push((r % radix) as u8);
1989            r /= radix;
1990        }
1991        digits = q;
1992    }
1993
1994    let mut r = digits.data[0];
1995    while r != 0 {
1996        res.push((r % radix) as u8);
1997        r /= radix;
1998    }
1999
2000    res
2001}
2002
2003pub fn to_radix_le(u: &BigUint, radix: u32) -> Vec<u8> {
2004    if u.is_zero() {
2005        vec![0]
2006    } else if radix.is_power_of_two() {
2007        // Powers of two can use bitwise masks and shifting instead of division
2008        let bits = ilog2(radix);
2009        if big_digit::BITS % bits == 0 {
2010            to_bitwise_digits_le(u, bits)
2011        } else {
2012            to_inexact_bitwise_digits_le(u, bits)
2013        }
2014    } else if radix == 10 {
2015        // 10 is so common that it's worth separating out for const-propagation.
2016        // Optimizers can often turn constant division into a faster multiplication.
2017        to_radix_digits_le(u, 10)
2018    } else {
2019        to_radix_digits_le(u, radix)
2020    }
2021}
2022
2023pub fn to_str_radix_reversed(u: &BigUint, radix: u32) -> Vec<u8> {
2024    assert!(2 <= radix && radix <= 36, "The radix must be within 2...36");
2025
2026    if u.is_zero() {
2027        return vec![b'0'];
2028    }
2029
2030    let mut res = to_radix_le(u, radix);
2031
2032    // Now convert everything to ASCII digits.
2033    for r in &mut res {
2034        debug_assert!((*r as u32) < radix);
2035        if *r < 10 {
2036            *r += b'0';
2037        } else {
2038            *r += b'a' - 10;
2039        }
2040    }
2041    res
2042}
2043
2044#[cfg(not(feature = "u64_digit"))]
2045#[inline]
2046fn ensure_big_digit(raw: Vec<u32>) -> SmallVec<[BigDigit; VEC_SIZE]> {
2047    raw.into()
2048}
2049
2050#[cfg(feature = "u64_digit")]
2051#[inline]
2052fn ensure_big_digit(raw: Vec<u32>) -> SmallVec<[BigDigit; VEC_SIZE]> {
2053    ensure_big_digit_slice(&raw)
2054}
2055
2056#[cfg(feature = "u64_digit")]
2057#[inline]
2058fn ensure_big_digit_slice(raw: &[u32]) -> SmallVec<[BigDigit; VEC_SIZE]> {
2059    raw.chunks(2)
2060        .map(|chunk| {
2061            // raw could have odd length
2062            if chunk.len() < 2 {
2063                chunk[0] as BigDigit
2064            } else {
2065                BigDigit::from(chunk[0]) | (BigDigit::from(chunk[1]) << 32)
2066            }
2067        })
2068        .collect()
2069}
2070
2071impl BigUint {
2072    /// Creates and initializes a `BigUint`.
2073    ///
2074    /// The digits are in little-endian base 2<sup>32</sup>.
2075    #[inline]
2076    pub fn new(digits: Vec<u32>) -> BigUint {
2077        Self::new_native(ensure_big_digit(digits))
2078    }
2079
2080    /// Creates and initializes a `BigUint`.
2081    ///
2082    /// The digits are in little-endian base matching `BigDigit`.
2083    #[inline]
2084    pub fn new_native(digits: SmallVec<[BigDigit; VEC_SIZE]>) -> BigUint {
2085        BigUint { data: digits }.normalized()
2086    }
2087
2088    /// Creates and initializes a `BigUint`.
2089    ///
2090    /// The digits are in little-endian base 2<sup>32</sup>.
2091    #[inline]
2092    pub fn from_slice(slice: &[u32]) -> BigUint {
2093        BigUint::new(slice.to_vec())
2094    }
2095
2096    /// Creates and initializes a `BigUint`.
2097    ///
2098    /// The digits are in little-endian base matching `BigDigit`
2099    #[inline]
2100    pub fn from_slice_native(slice: &[BigDigit]) -> BigUint {
2101        BigUint::new_native(slice.into())
2102    }
2103
2104    pub fn get_limb(&self, i: usize) -> BigDigit {
2105        self.data[i]
2106    }
2107
2108    /// Assign a value to a `BigUint`.
2109    ///
2110    /// The digits are in little-endian base 2<sup>32</sup>.
2111    #[cfg(not(feature = "u64_digit"))]
2112    #[inline]
2113    pub fn assign_from_slice(&mut self, slice: &[u32]) {
2114        self.assign_from_slice_native(slice);
2115    }
2116    #[cfg(feature = "u64_digit")]
2117    #[inline]
2118    pub fn assign_from_slice(&mut self, slice: &[u32]) {
2119        let slice_digits = ensure_big_digit_slice(slice);
2120        self.assign_from_slice_native(&slice_digits);
2121    }
2122
2123    /// Assign a value to a `BigUint`.
2124    ///
2125    /// The digits are in little-endian with the base matching `BigDigit`.
2126    #[inline]
2127    pub fn assign_from_slice_native(&mut self, slice: &[BigDigit]) {
2128        self.data.resize(slice.len(), 0);
2129        self.data.clone_from_slice(slice);
2130        self.normalize();
2131    }
2132
2133    /// Creates and initializes a `BigUint`.
2134    ///
2135    /// The bytes are in big-endian byte order.
2136    ///
2137    /// # Examples
2138    ///
2139    /// ```
2140    /// use num_bigint_dig::BigUint;
2141    ///
2142    /// assert_eq!(BigUint::from_bytes_be(b"A"),
2143    ///            BigUint::parse_bytes(b"65", 10).unwrap());
2144    /// assert_eq!(BigUint::from_bytes_be(b"AA"),
2145    ///            BigUint::parse_bytes(b"16705", 10).unwrap());
2146    /// assert_eq!(BigUint::from_bytes_be(b"AB"),
2147    ///            BigUint::parse_bytes(b"16706", 10).unwrap());
2148    /// assert_eq!(BigUint::from_bytes_be(b"Hello world!"),
2149    ///            BigUint::parse_bytes(b"22405534230753963835153736737", 10).unwrap());
2150    /// ```
2151    #[inline]
2152    pub fn from_bytes_be(bytes: &[u8]) -> BigUint {
2153        if bytes.is_empty() {
2154            Zero::zero()
2155        } else {
2156            let mut v = bytes.to_vec();
2157            v.reverse();
2158            BigUint::from_bytes_le(&*v)
2159        }
2160    }
2161
2162    /// Creates and initializes a `BigUint`.
2163    ///
2164    /// The bytes are in little-endian byte order.
2165    #[inline]
2166    pub fn from_bytes_le(bytes: &[u8]) -> BigUint {
2167        if bytes.is_empty() {
2168            Zero::zero()
2169        } else {
2170            from_bitwise_digits_le(bytes, 8)
2171        }
2172    }
2173
2174    /// Creates and initializes a `BigUint`. The input slice must contain
2175    /// ascii/utf8 characters in [0-9a-zA-Z].
2176    /// `radix` must be in the range `2...36`.
2177    ///
2178    /// The function `from_str_radix` from the `Num` trait provides the same logic
2179    /// for `&str` buffers.
2180    ///
2181    /// # Examples
2182    ///
2183    /// ```
2184    /// use num_bigint_dig::{BigUint, ToBigUint};
2185    ///
2186    /// assert_eq!(BigUint::parse_bytes(b"1234", 10), ToBigUint::to_biguint(&1234));
2187    /// assert_eq!(BigUint::parse_bytes(b"ABCD", 16), ToBigUint::to_biguint(&0xABCD));
2188    /// assert_eq!(BigUint::parse_bytes(b"G", 16), None);
2189    /// ```
2190    #[inline]
2191    pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigUint> {
2192        str::from_utf8(buf)
2193            .ok()
2194            .and_then(|s| BigUint::from_str_radix(s, radix).ok())
2195    }
2196
2197    /// Creates and initializes a `BigUint`. Each u8 of the input slice is
2198    /// interpreted as one digit of the number
2199    /// and must therefore be less than `radix`.
2200    ///
2201    /// The bytes are in big-endian byte order.
2202    /// `radix` must be in the range `2...256`.
2203    ///
2204    /// # Examples
2205    ///
2206    /// ```
2207    /// use num_bigint_dig::{BigUint};
2208    ///
2209    /// let inbase190 = &[15, 33, 125, 12, 14];
2210    /// let a = BigUint::from_radix_be(inbase190, 190).unwrap();
2211    /// assert_eq!(a.to_radix_be(190), inbase190);
2212    /// ```
2213    pub fn from_radix_be(buf: &[u8], radix: u32) -> Option<BigUint> {
2214        assert!(
2215            2 <= radix && radix <= 256,
2216            "The radix must be within 2...256"
2217        );
2218
2219        if radix != 256 && buf.iter().any(|&b| b >= radix as u8) {
2220            return None;
2221        }
2222
2223        let res = if radix.is_power_of_two() {
2224            // Powers of two can use bitwise masks and shifting instead of multiplication
2225            let bits = ilog2(radix);
2226            let mut v = Vec::from(buf);
2227            v.reverse();
2228            if big_digit::BITS % bits == 0 {
2229                from_bitwise_digits_le(&v, bits)
2230            } else {
2231                from_inexact_bitwise_digits_le(&v, bits)
2232            }
2233        } else {
2234            from_radix_digits_be(buf, radix)
2235        };
2236
2237        Some(res)
2238    }
2239
2240    /// Creates and initializes a `BigUint`. Each u8 of the input slice is
2241    /// interpreted as one digit of the number
2242    /// and must therefore be less than `radix`.
2243    ///
2244    /// The bytes are in little-endian byte order.
2245    /// `radix` must be in the range `2...256`.
2246    ///
2247    /// # Examples
2248    ///
2249    /// ```
2250    /// use num_bigint_dig::{BigUint};
2251    ///
2252    /// let inbase190 = &[14, 12, 125, 33, 15];
2253    /// let a = BigUint::from_radix_be(inbase190, 190).unwrap();
2254    /// assert_eq!(a.to_radix_be(190), inbase190);
2255    /// ```
2256    pub fn from_radix_le(buf: &[u8], radix: u32) -> Option<BigUint> {
2257        assert!(
2258            2 <= radix && radix <= 256,
2259            "The radix must be within 2...256"
2260        );
2261
2262        if radix != 256 && buf.iter().any(|&b| b >= radix as u8) {
2263            return None;
2264        }
2265
2266        let res = if radix.is_power_of_two() {
2267            // Powers of two can use bitwise masks and shifting instead of multiplication
2268            let bits = ilog2(radix);
2269            if big_digit::BITS % bits == 0 {
2270                from_bitwise_digits_le(buf, bits)
2271            } else {
2272                from_inexact_bitwise_digits_le(buf, bits)
2273            }
2274        } else {
2275            let mut v = Vec::from(buf);
2276            v.reverse();
2277            from_radix_digits_be(&v, radix)
2278        };
2279
2280        Some(res)
2281    }
2282
2283    /// Returns the byte representation of the `BigUint` in big-endian byte order.
2284    ///
2285    /// # Examples
2286    ///
2287    /// ```
2288    /// use num_bigint_dig::BigUint;
2289    ///
2290    /// let i = BigUint::parse_bytes(b"1125", 10).unwrap();
2291    /// assert_eq!(i.to_bytes_be(), vec![4, 101]);
2292    /// ```
2293    #[inline]
2294    pub fn to_bytes_be(&self) -> Vec<u8> {
2295        let mut v = self.to_bytes_le();
2296        v.reverse();
2297        v
2298    }
2299
2300    /// Returns the byte representation of the `BigUint` in little-endian byte order.
2301    ///
2302    /// # Examples
2303    ///
2304    /// ```
2305    /// use num_bigint_dig::BigUint;
2306    ///
2307    /// let i = BigUint::parse_bytes(b"1125", 10).unwrap();
2308    /// assert_eq!(i.to_bytes_le(), vec![101, 4]);
2309    /// ```
2310    #[inline]
2311    pub fn to_bytes_le(&self) -> Vec<u8> {
2312        if self.is_zero() {
2313            vec![0]
2314        } else {
2315            to_bitwise_digits_le(self, 8)
2316        }
2317    }
2318
2319    /// Returns the integer formatted as a string in the given radix.
2320    /// `radix` must be in the range `2...36`.
2321    ///
2322    /// # Examples
2323    ///
2324    /// ```
2325    /// use num_bigint_dig::BigUint;
2326    ///
2327    /// let i = BigUint::parse_bytes(b"ff", 16).unwrap();
2328    /// assert_eq!(i.to_str_radix(16), "ff");
2329    /// ```
2330    #[inline]
2331    pub fn to_str_radix(&self, radix: u32) -> String {
2332        let mut v = to_str_radix_reversed(self, radix);
2333        v.reverse();
2334        unsafe { String::from_utf8_unchecked(v) }
2335    }
2336
2337    /// Returns the integer in the requested base in big-endian digit order.
2338    /// The output is not given in a human readable alphabet but as a zero
2339    /// based u8 number.
2340    /// `radix` must be in the range `2...256`.
2341    ///
2342    /// # Examples
2343    ///
2344    /// ```
2345    /// use num_bigint_dig::BigUint;
2346    ///
2347    /// assert_eq!(BigUint::from(0xFFFFu64).to_radix_be(159),
2348    ///            vec![2, 94, 27]);
2349    /// // 0xFFFF = 65535 = 2*(159^2) + 94*159 + 27
2350    /// ```
2351    #[inline]
2352    pub fn to_radix_be(&self, radix: u32) -> Vec<u8> {
2353        let mut v = to_radix_le(self, radix);
2354        v.reverse();
2355        v
2356    }
2357
2358    /// Returns the integer in the requested base in little-endian digit order.
2359    /// The output is not given in a human readable alphabet but as a zero
2360    /// based u8 number.
2361    /// `radix` must be in the range `2...256`.
2362    ///
2363    /// # Examples
2364    ///
2365    /// ```
2366    /// use num_bigint_dig::BigUint;
2367    ///
2368    /// assert_eq!(BigUint::from(0xFFFFu64).to_radix_le(159),
2369    ///            vec![27, 94, 2]);
2370    /// // 0xFFFF = 65535 = 27 + 94*159 + 2*(159^2)
2371    /// ```
2372    #[inline]
2373    pub fn to_radix_le(&self, radix: u32) -> Vec<u8> {
2374        to_radix_le(self, radix)
2375    }
2376
2377    /// Determines the fewest bits necessary to express the `BigUint`.
2378    #[inline]
2379    pub fn bits(&self) -> usize {
2380        if self.is_zero() {
2381            return 0;
2382        }
2383        let zeros = self.data.last().unwrap().leading_zeros();
2384        self.data.len() * big_digit::BITS - zeros as usize
2385    }
2386
2387    /// Strips off trailing zero bigdigits - comparisons require the last element in the vector to
2388    /// be nonzero.
2389    #[inline]
2390    pub(crate) fn normalize(&mut self) {
2391        while let Some(&0) = self.data.last() {
2392            self.data.pop();
2393        }
2394    }
2395
2396    /// Returns a normalized `BigUint`.
2397    #[inline]
2398    pub(crate) fn normalized(mut self) -> BigUint {
2399        self.normalize();
2400        self
2401    }
2402
2403    /// Returns `(self ^ exponent) % modulus`.
2404    ///
2405    /// Panics if the modulus is zero.
2406    pub fn modpow(&self, exponent: &Self, modulus: &Self) -> Self {
2407        assert!(!modulus.is_zero(), "divide by zero!");
2408
2409        // For an odd modulus, we can use Montgomery multiplication in base 2^32.
2410        if modulus.is_odd() {
2411            return monty_modpow(self, exponent, modulus);
2412        }
2413
2414        // Otherwise do basically the same as `num::pow`, but with a modulus.
2415        let one = BigUint::one();
2416        if exponent.is_zero() {
2417            return one;
2418        }
2419
2420        let mut base = self % modulus;
2421        let mut exp = exponent.clone();
2422        while exp.is_even() {
2423            base = &base * &base % modulus;
2424            exp >>= 1;
2425        }
2426        if exp == one {
2427            return base;
2428        }
2429
2430        let mut acc = base.clone();
2431        while exp > one {
2432            exp >>= 1;
2433            base = &base * &base % modulus;
2434            if exp.is_odd() {
2435                acc = acc * &base % modulus;
2436            }
2437        }
2438        acc
2439    }
2440
2441    /// Returns the truncated principal square root of `self` --
2442    /// see [Roots::sqrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.sqrt)
2443    pub fn sqrt(&self) -> Self {
2444        Roots::sqrt(self)
2445    }
2446
2447    /// Returns the truncated principal cube root of `self` --
2448    /// see [Roots::cbrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.cbrt).
2449    pub fn cbrt(&self) -> Self {
2450        Roots::cbrt(self)
2451    }
2452
2453    /// Returns the truncated principal `n`th root of `self` --
2454    /// see [Roots::nth_root](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#tymethod.nth_root).
2455    pub fn nth_root(&self, n: u32) -> Self {
2456        Roots::nth_root(self, n)
2457    }
2458
2459    pub fn trailing_zeros(&self) -> Option<usize> {
2460        trailing_zeros(self)
2461    }
2462
2463    /// Sets the value to the provided digit, reusing internal storage.
2464    pub fn set_digit(&mut self, digit: BigDigit) {
2465        if self.is_zero() {
2466            self.data.resize(1, digit);
2467        } else {
2468            self.data.resize(1, 0);
2469            self.data[0] = digit;
2470        }
2471    }
2472}
2473
2474/// Returns the number of least-significant bits that are zero,
2475/// or `None` if the entire number is zero.
2476pub fn trailing_zeros(u: &BigUint) -> Option<usize> {
2477    u.data
2478        .iter()
2479        .enumerate()
2480        .find(|&(_, &digit)| digit != 0)
2481        .map(|(i, digit)| i * big_digit::BITS + digit.trailing_zeros() as usize)
2482}
2483
2484impl_sum_iter_type!(BigUint);
2485impl_product_iter_type!(BigUint);
2486
2487pub trait IntDigits {
2488    fn digits(&self) -> &[BigDigit];
2489    fn digits_mut(&mut self) -> &mut SmallVec<[BigDigit; VEC_SIZE]>;
2490    fn normalize(&mut self);
2491    fn capacity(&self) -> usize;
2492    fn len(&self) -> usize;
2493}
2494
2495impl IntDigits for BigUint {
2496    #[inline]
2497    fn digits(&self) -> &[BigDigit] {
2498        &self.data
2499    }
2500    #[inline]
2501    fn digits_mut(&mut self) -> &mut SmallVec<[BigDigit; VEC_SIZE]> {
2502        &mut self.data
2503    }
2504    #[inline]
2505    fn normalize(&mut self) {
2506        self.normalize();
2507    }
2508    #[inline]
2509    fn capacity(&self) -> usize {
2510        self.data.capacity()
2511    }
2512    #[inline]
2513    fn len(&self) -> usize {
2514        self.data.len()
2515    }
2516}
2517
2518/// Combine four `u32`s into a single `u128`.
2519#[cfg(has_i128)]
2520#[inline]
2521#[allow(dead_code)]
2522fn u32_to_u128(a: u32, b: u32, c: u32, d: u32) -> u128 {
2523    u128::from(d) | (u128::from(c) << 32) | (u128::from(b) << 64) | (u128::from(a) << 96)
2524}
2525
2526/// Split a single `u128` into four `u32`.
2527#[cfg(has_i128)]
2528#[inline]
2529#[allow(dead_code)]
2530fn u32_from_u128(n: u128) -> (u32, u32, u32, u32) {
2531    (
2532        (n >> 96) as u32,
2533        (n >> 64) as u32,
2534        (n >> 32) as u32,
2535        n as u32,
2536    )
2537}
2538
2539#[cfg(feature = "serde")]
2540#[cfg(not(feature = "u64_digit"))]
2541impl serde::Serialize for BigUint {
2542    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2543    where
2544        S: serde::Serializer,
2545    {
2546        // Note: do not change the serialization format, or it may break forward
2547        // and backward compatibility of serialized data!  If we ever change the
2548        // internal representation, we should still serialize in base-`u32`.
2549        let data: &[u32] = &self.data.as_slice();
2550        data.serialize(serializer)
2551    }
2552}
2553
2554#[cfg(feature = "serde")]
2555#[cfg(feature = "u64_digit")]
2556impl serde::Serialize for BigUint {
2557    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2558    where
2559        S: serde::Serializer,
2560    {
2561        let last = if self.data.is_empty() {
2562            0
2563        } else {
2564            self.data.len() - 1
2565        };
2566        let data: Vec<u32> = self
2567            .data
2568            .iter()
2569            .enumerate()
2570            .flat_map(|(i, n)| {
2571                if i == last && n < &(u32::MAX as u64) {
2572                    vec![*n as u32]
2573                } else {
2574                    vec![*n as u32, (n >> 32) as u32]
2575                }
2576            })
2577            .collect();
2578        data.serialize(serializer)
2579    }
2580}
2581
2582#[cfg(feature = "serde")]
2583impl<'de> serde::Deserialize<'de> for BigUint {
2584    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2585    where
2586        D: serde::Deserializer<'de>,
2587    {
2588        let data: Vec<u32> = Vec::deserialize(deserializer)?;
2589        Ok(BigUint::new(data))
2590    }
2591}
2592
2593/// Returns the greatest power of the radix <= big_digit::BASE
2594#[inline]
2595fn get_radix_base(radix: u32) -> (BigDigit, usize) {
2596    debug_assert!(
2597        2 <= radix && radix <= 256,
2598        "The radix must be within 2...256"
2599    );
2600    debug_assert!(!radix.is_power_of_two());
2601
2602    // To generate this table:
2603    //    for radix in 2u64..257 {
2604    //        let mut power = big_digit::BITS / fls(radix as u64);
2605    //        let mut base = radix.pow(power as u32);
2606    //
2607    //        while let Some(b) = base.checked_mul(radix) {
2608    //            if b > big_digit::MAX {
2609    //                break;
2610    //            }
2611    //            base = b;
2612    //            power += 1;
2613    //        }
2614    //
2615    //        println!("({:10}, {:2}), // {:2}", base, power, radix);
2616    //    }
2617    // and
2618    //    for radix in 2u64..257 {
2619    //        let mut power = 64 / fls(radix as u64);
2620    //        let mut base = radix.pow(power as u32);
2621    //
2622    //        while let Some(b) = base.checked_mul(radix) {
2623    //            base = b;
2624    //            power += 1;
2625    //        }
2626    //
2627    //        println!("({:20}, {:2}), // {:2}", base, power, radix);
2628    //    }
2629    match big_digit::BITS {
2630        32 => {
2631            const BASES: [(u32, usize); 257] = [
2632                (0, 0),
2633                (0, 0),
2634                (0, 0),              //  2
2635                (3_486_784_401, 20), //  3
2636                (0, 0),              //  4
2637                (1_220_703_125, 13), //  5
2638                (2_176_782_336, 12), //  6
2639                (1_977_326_743, 11), //  7
2640                (0, 0),              //  8
2641                (3_486_784_401, 10), //  9
2642                (1_000_000_000, 9),  // 10
2643                (2_357_947_691, 9),  // 11
2644                (429_981_696, 8),    // 12
2645                (815_730_721, 8),    // 13
2646                (1_475_789_056, 8),  // 14
2647                (2_562_890_625, 8),  // 15
2648                (0, 0),              // 16
2649                (410_338_673, 7),    // 17
2650                (612_220_032, 7),    // 18
2651                (893_871_739, 7),    // 19
2652                (1_280_000_000, 7),  // 20
2653                (1_801_088_541, 7),  // 21
2654                (2_494_357_888, 7),  // 22
2655                (3_404_825_447, 7),  // 23
2656                (191_102_976, 6),    // 24
2657                (244_140_625, 6),    // 25
2658                (308_915_776, 6),    // 26
2659                (387_420_489, 6),    // 27
2660                (481_890_304, 6),    // 28
2661                (594_823_321, 6),    // 29
2662                (729_000_000, 6),    // 30
2663                (887_503_681, 6),    // 31
2664                (0, 0),              // 32
2665                (1_291_467_969, 6),  // 33
2666                (1_544_804_416, 6),  // 34
2667                (1_838_265_625, 6),  // 35
2668                (2_176_782_336, 6),  // 36
2669                (2_565_726_409, 6),  // 37
2670                (3_010_936_384, 6),  // 38
2671                (3_518_743_761, 6),  // 39
2672                (4_096_000_000, 6),  // 40
2673                (115_856_201, 5),    // 41
2674                (130_691_232, 5),    // 42
2675                (147_008_443, 5),    // 43
2676                (164_916_224, 5),    // 44
2677                (184_528_125, 5),    // 45
2678                (205_962_976, 5),    // 46
2679                (229_345_007, 5),    // 47
2680                (254_803_968, 5),    // 48
2681                (282_475_249, 5),    // 49
2682                (312_500_000, 5),    // 50
2683                (345_025_251, 5),    // 51
2684                (380_204_032, 5),    // 52
2685                (418_195_493, 5),    // 53
2686                (459_165_024, 5),    // 54
2687                (503_284_375, 5),    // 55
2688                (550_731_776, 5),    // 56
2689                (601_692_057, 5),    // 57
2690                (656_356_768, 5),    // 58
2691                (714_924_299, 5),    // 59
2692                (777_600_000, 5),    // 60
2693                (844_596_301, 5),    // 61
2694                (916_132_832, 5),    // 62
2695                (992_436_543, 5),    // 63
2696                (0, 0),              // 64
2697                (1_160_290_625, 5),  // 65
2698                (1_252_332_576, 5),  // 66
2699                (1_350_125_107, 5),  // 67
2700                (1_453_933_568, 5),  // 68
2701                (1_564_031_349, 5),  // 69
2702                (1_680_700_000, 5),  // 70
2703                (1_804_229_351, 5),  // 71
2704                (1_934_917_632, 5),  // 72
2705                (2_073_071_593, 5),  // 73
2706                (2_219_006_624, 5),  // 74
2707                (2_373_046_875, 5),  // 75
2708                (2_535_525_376, 5),  // 76
2709                (2_706_784_157, 5),  // 77
2710                (2_887_174_368, 5),  // 78
2711                (3_077_056_399, 5),  // 79
2712                (3_276_800_000, 5),  // 80
2713                (3_486_784_401, 5),  // 81
2714                (3_707_398_432, 5),  // 82
2715                (3_939_040_643, 5),  // 83
2716                (4_182_119_424, 5),  // 84
2717                (52_200_625, 4),     // 85
2718                (54_700_816, 4),     // 86
2719                (57_289_761, 4),     // 87
2720                (59_969_536, 4),     // 88
2721                (62_742_241, 4),     // 89
2722                (65_610_000, 4),     // 90
2723                (68_574_961, 4),     // 91
2724                (71_639_296, 4),     // 92
2725                (74_805_201, 4),     // 93
2726                (78_074_896, 4),     // 94
2727                (81_450_625, 4),     // 95
2728                (84_934_656, 4),     // 96
2729                (88_529_281, 4),     // 97
2730                (92_236_816, 4),     // 98
2731                (96_059_601, 4),     // 99
2732                (100_000_000, 4),    // 100
2733                (104_060_401, 4),    // 101
2734                (108_243_216, 4),    // 102
2735                (112_550_881, 4),    // 103
2736                (116_985_856, 4),    // 104
2737                (121_550_625, 4),    // 105
2738                (126_247_696, 4),    // 106
2739                (131_079_601, 4),    // 107
2740                (136_048_896, 4),    // 108
2741                (141_158_161, 4),    // 109
2742                (146_410_000, 4),    // 110
2743                (151_807_041, 4),    // 111
2744                (157_351_936, 4),    // 112
2745                (163_047_361, 4),    // 113
2746                (168_896_016, 4),    // 114
2747                (174_900_625, 4),    // 115
2748                (181_063_936, 4),    // 116
2749                (187_388_721, 4),    // 117
2750                (193_877_776, 4),    // 118
2751                (200_533_921, 4),    // 119
2752                (207_360_000, 4),    // 120
2753                (214_358_881, 4),    // 121
2754                (221_533_456, 4),    // 122
2755                (228_886_641, 4),    // 123
2756                (236_421_376, 4),    // 124
2757                (244_140_625, 4),    // 125
2758                (252_047_376, 4),    // 126
2759                (260_144_641, 4),    // 127
2760                (0, 0),              // 128
2761                (276_922_881, 4),    // 129
2762                (285_610_000, 4),    // 130
2763                (294_499_921, 4),    // 131
2764                (303_595_776, 4),    // 132
2765                (312_900_721, 4),    // 133
2766                (322_417_936, 4),    // 134
2767                (332_150_625, 4),    // 135
2768                (342_102_016, 4),    // 136
2769                (352_275_361, 4),    // 137
2770                (362_673_936, 4),    // 138
2771                (373_301_041, 4),    // 139
2772                (384_160_000, 4),    // 140
2773                (395_254_161, 4),    // 141
2774                (406_586_896, 4),    // 142
2775                (418_161_601, 4),    // 143
2776                (429_981_696, 4),    // 144
2777                (442_050_625, 4),    // 145
2778                (454_371_856, 4),    // 146
2779                (466_948_881, 4),    // 147
2780                (479_785_216, 4),    // 148
2781                (492_884_401, 4),    // 149
2782                (506_250_000, 4),    // 150
2783                (519_885_601, 4),    // 151
2784                (533_794_816, 4),    // 152
2785                (547_981_281, 4),    // 153
2786                (562_448_656, 4),    // 154
2787                (577_200_625, 4),    // 155
2788                (592_240_896, 4),    // 156
2789                (607_573_201, 4),    // 157
2790                (623_201_296, 4),    // 158
2791                (639_128_961, 4),    // 159
2792                (655_360_000, 4),    // 160
2793                (671_898_241, 4),    // 161
2794                (688_747_536, 4),    // 162
2795                (705_911_761, 4),    // 163
2796                (723_394_816, 4),    // 164
2797                (741_200_625, 4),    // 165
2798                (759_333_136, 4),    // 166
2799                (777_796_321, 4),    // 167
2800                (796_594_176, 4),    // 168
2801                (815_730_721, 4),    // 169
2802                (835_210_000, 4),    // 170
2803                (855_036_081, 4),    // 171
2804                (875_213_056, 4),    // 172
2805                (895_745_041, 4),    // 173
2806                (916_636_176, 4),    // 174
2807                (937_890_625, 4),    // 175
2808                (959_512_576, 4),    // 176
2809                (981_506_241, 4),    // 177
2810                (1_003_875_856, 4),  // 178
2811                (1_026_625_681, 4),  // 179
2812                (1_049_760_000, 4),  // 180
2813                (1_073_283_121, 4),  // 181
2814                (1_097_199_376, 4),  // 182
2815                (1_121_513_121, 4),  // 183
2816                (1_146_228_736, 4),  // 184
2817                (1_171_350_625, 4),  // 185
2818                (1_196_883_216, 4),  // 186
2819                (1_222_830_961, 4),  // 187
2820                (1_249_198_336, 4),  // 188
2821                (1_275_989_841, 4),  // 189
2822                (1_303_210_000, 4),  // 190
2823                (1_330_863_361, 4),  // 191
2824                (1_358_954_496, 4),  // 192
2825                (1_387_488_001, 4),  // 193
2826                (1_416_468_496, 4),  // 194
2827                (1_445_900_625, 4),  // 195
2828                (1_475_789_056, 4),  // 196
2829                (1_506_138_481, 4),  // 197
2830                (1_536_953_616, 4),  // 198
2831                (1_568_239_201, 4),  // 199
2832                (1_600_000_000, 4),  // 200
2833                (1_632_240_801, 4),  // 201
2834                (1_664_966_416, 4),  // 202
2835                (1_698_181_681, 4),  // 203
2836                (1_731_891_456, 4),  // 204
2837                (1_766_100_625, 4),  // 205
2838                (1_800_814_096, 4),  // 206
2839                (1_836_036_801, 4),  // 207
2840                (1_871_773_696, 4),  // 208
2841                (1_908_029_761, 4),  // 209
2842                (1_944_810_000, 4),  // 210
2843                (1_982_119_441, 4),  // 211
2844                (2_019_963_136, 4),  // 212
2845                (2_058_346_161, 4),  // 213
2846                (2_097_273_616, 4),  // 214
2847                (2_136_750_625, 4),  // 215
2848                (2_176_782_336, 4),  // 216
2849                (2_217_373_921, 4),  // 217
2850                (2_258_530_576, 4),  // 218
2851                (2_300_257_521, 4),  // 219
2852                (2_342_560_000, 4),  // 220
2853                (2_385_443_281, 4),  // 221
2854                (2_428_912_656, 4),  // 222
2855                (2_472_973_441, 4),  // 223
2856                (2_517_630_976, 4),  // 224
2857                (2_562_890_625, 4),  // 225
2858                (2_608_757_776, 4),  // 226
2859                (2_655_237_841, 4),  // 227
2860                (2_702_336_256, 4),  // 228
2861                (2_750_058_481, 4),  // 229
2862                (2_798_410_000, 4),  // 230
2863                (2_847_396_321, 4),  // 231
2864                (2_897_022_976, 4),  // 232
2865                (2_947_295_521, 4),  // 233
2866                (2_998_219_536, 4),  // 234
2867                (3_049_800_625, 4),  // 235
2868                (3_102_044_416, 4),  // 236
2869                (3_154_956_561, 4),  // 237
2870                (3_208_542_736, 4),  // 238
2871                (3_262_808_641, 4),  // 239
2872                (3_317_760_000, 4),  // 240
2873                (3_373_402_561, 4),  // 241
2874                (3_429_742_096, 4),  // 242
2875                (3_486_784_401, 4),  // 243
2876                (3_544_535_296, 4),  // 244
2877                (3_603_000_625, 4),  // 245
2878                (3_662_186_256, 4),  // 246
2879                (3_722_098_081, 4),  // 247
2880                (3_782_742_016, 4),  // 248
2881                (3_844_124_001, 4),  // 249
2882                (3_906_250_000, 4),  // 250
2883                (3_969_126_001, 4),  // 251
2884                (4_032_758_016, 4),  // 252
2885                (4_097_152_081, 4),  // 253
2886                (4_162_314_256, 4),  // 254
2887                (4_228_250_625, 4),  // 255
2888                (0, 0),              // 256
2889            ];
2890
2891            let (base, power) = BASES[radix as usize];
2892            (base as BigDigit, power)
2893        }
2894        64 => {
2895            const BASES: [(u64, usize); 257] = [
2896                (0, 0),
2897                (0, 0),
2898                (9_223_372_036_854_775_808, 63),  //  2
2899                (12_157_665_459_056_928_801, 40), //  3
2900                (4_611_686_018_427_387_904, 31),  //  4
2901                (7_450_580_596_923_828_125, 27),  //  5
2902                (4_738_381_338_321_616_896, 24),  //  6
2903                (3_909_821_048_582_988_049, 22),  //  7
2904                (9_223_372_036_854_775_808, 21),  //  8
2905                (12_157_665_459_056_928_801, 20), //  9
2906                (10_000_000_000_000_000_000, 19), // 10
2907                (5_559_917_313_492_231_481, 18),  // 11
2908                (2_218_611_106_740_436_992, 17),  // 12
2909                (8_650_415_919_381_337_933, 17),  // 13
2910                (2_177_953_337_809_371_136, 16),  // 14
2911                (6_568_408_355_712_890_625, 16),  // 15
2912                (1_152_921_504_606_846_976, 15),  // 16
2913                (2_862_423_051_509_815_793, 15),  // 17
2914                (6_746_640_616_477_458_432, 15),  // 18
2915                (15_181_127_029_874_798_299, 15), // 19
2916                (1_638_400_000_000_000_000, 14),  // 20
2917                (3_243_919_932_521_508_681, 14),  // 21
2918                (6_221_821_273_427_820_544, 14),  // 22
2919                (11_592_836_324_538_749_809, 14), // 23
2920                (876_488_338_465_357_824, 13),    // 24
2921                (1_490_116_119_384_765_625, 13),  // 25
2922                (2_481_152_873_203_736_576, 13),  // 26
2923                (4_052_555_153_018_976_267, 13),  // 27
2924                (6_502_111_422_497_947_648, 13),  // 28
2925                (10_260_628_712_958_602_189, 13), // 29
2926                (15_943_230_000_000_000_000, 13), // 30
2927                (787_662_783_788_549_761, 12),    // 31
2928                (1_152_921_504_606_846_976, 12),  // 32
2929                (1_667_889_514_952_984_961, 12),  // 33
2930                (2_386_420_683_693_101_056, 12),  // 34
2931                (3_379_220_508_056_640_625, 12),  // 35
2932                (4_738_381_338_321_616_896, 12),  // 36
2933                (6_582_952_005_840_035_281, 12),  // 37
2934                (9_065_737_908_494_995_456, 12),  // 38
2935                (12_381_557_655_576_425_121, 12), // 39
2936                (16_777_216_000_000_000_000, 12), // 40
2937                (550_329_031_716_248_441, 11),    // 41
2938                (717_368_321_110_468_608, 11),    // 42
2939                (929_293_739_471_222_707, 11),    // 43
2940                (1_196_683_881_290_399_744, 11),  // 44
2941                (1_532_278_301_220_703_125, 11),  // 45
2942                (1_951_354_384_207_722_496, 11),  // 46
2943                (2_472_159_215_084_012_303, 11),  // 47
2944                (3_116_402_981_210_161_152, 11),  // 48
2945                (3_909_821_048_582_988_049, 11),  // 49
2946                (4_882_812_500_000_000_000, 11),  // 50
2947                (6_071_163_615_208_263_051, 11),  // 51
2948                (7_516_865_509_350_965_248, 11),  // 52
2949                (9_269_035_929_372_191_597, 11),  // 53
2950                (11_384_956_040_305_711_104, 11), // 54
2951                (13_931_233_916_552_734_375, 11), // 55
2952                (16_985_107_389_382_393_856, 11), // 56
2953                (362_033_331_456_891_249, 10),    // 57
2954                (430_804_206_899_405_824, 10),    // 58
2955                (511_116_753_300_641_401, 10),    // 59
2956                (604_661_760_000_000_000, 10),    // 60
2957                (713_342_911_662_882_601, 10),    // 61
2958                (839_299_365_868_340_224, 10),    // 62
2959                (984_930_291_881_790_849, 10),    // 63
2960                (1_152_921_504_606_846_976, 10),  // 64
2961                (1_346_274_334_462_890_625, 10),  // 65
2962                (1_568_336_880_910_795_776, 10),  // 66
2963                (1_822_837_804_551_761_449, 10),  // 67
2964                (2_113_922_820_157_210_624, 10),  // 68
2965                (2_446_194_060_654_759_801, 10),  // 69
2966                (2_824_752_490_000_000_000, 10),  // 70
2967                (3_255_243_551_009_881_201, 10),  // 71
2968                (3_743_906_242_624_487_424, 10),  // 72
2969                (4_297_625_829_703_557_649, 10),  // 73
2970                (4_923_990_397_355_877_376, 10),  // 74
2971                (5_631_351_470_947_265_625, 10),  // 75
2972                (6_428_888_932_339_941_376, 10),  // 76
2973                (7_326_680_472_586_200_649, 10),  // 77
2974                (8_335_775_831_236_199_424, 10),  // 78
2975                (9_468_276_082_626_847_201, 10),  // 79
2976                (10_737_418_240_000_000_000, 10), // 80
2977                (12_157_665_459_056_928_801, 10), // 81
2978                (13_744_803_133_596_058_624, 10), // 82
2979                (15_516_041_187_205_853_449, 10), // 83
2980                (17_490_122_876_598_091_776, 10), // 84
2981                (231_616_946_283_203_125, 9),     // 85
2982                (257_327_417_311_663_616, 9),     // 86
2983                (285_544_154_243_029_527, 9),     // 87
2984                (316_478_381_828_866_048, 9),     // 88
2985                (350_356_403_707_485_209, 9),     // 89
2986                (387_420_489_000_000_000, 9),     // 90
2987                (427_929_800_129_788_411, 9),     // 91
2988                (472_161_363_286_556_672, 9),     // 92
2989                (520_411_082_988_487_293, 9),     // 93
2990                (572_994_802_228_616_704, 9),     // 94
2991                (630_249_409_724_609_375, 9),     // 95
2992                (692_533_995_824_480_256, 9),     // 96
2993                (760_231_058_654_565_217, 9),     // 97
2994                (833_747_762_130_149_888, 9),     // 98
2995                (913_517_247_483_640_899, 9),     // 99
2996                (1_000_000_000_000_000_000, 9),   // 100
2997                (1_093_685_272_684_360_901, 9),   // 101
2998                (1_195_092_568_622_310_912, 9),   // 102
2999                (1_304_773_183_829_244_583, 9),   // 103
3000                (1_423_311_812_421_484_544, 9),   // 104
3001                (1_551_328_215_978_515_625, 9),   // 105
3002                (1_689_478_959_002_692_096, 9),   // 106
3003                (1_838_459_212_420_154_507, 9),   // 107
3004                (1_999_004_627_104_432_128, 9),   // 108
3005                (2_171_893_279_442_309_389, 9),   // 109
3006                (2_357_947_691_000_000_000, 9),   // 110
3007                (2_558_036_924_386_500_591, 9),   // 111
3008                (2_773_078_757_450_186_752, 9),   // 112
3009                (3_004_041_937_984_268_273, 9),   // 113
3010                (3_251_948_521_156_637_184, 9),   // 114
3011                (3_517_876_291_919_921_875, 9),   // 115
3012                (3_802_961_274_698_203_136, 9),   // 116
3013                (4_108_400_332_687_853_397, 9),   // 117
3014                (4_435_453_859_151_328_768, 9),   // 118
3015                (4_785_448_563_124_474_679, 9),   // 119
3016                (5_159_780_352_000_000_000, 9),   // 120
3017                (5_559_917_313_492_231_481, 9),   // 121
3018                (5_987_402_799_531_080_192, 9),   // 122
3019                (6_443_858_614_676_334_363, 9),   // 123
3020                (6_930_988_311_686_938_624, 9),   // 124
3021                (7_450_580_596_923_828_125, 9),   // 125
3022                (8_004_512_848_309_157_376, 9),   // 126
3023                (8_594_754_748_609_397_887, 9),   // 127
3024                (9_223_372_036_854_775_808, 9),   // 128
3025                (9_892_530_380_752_880_769, 9),   // 129
3026                (10_604_499_373_000_000_000, 9),  // 130
3027                (11_361_656_654_439_817_571, 9),  // 131
3028                (12_166_492_167_065_567_232, 9),  // 132
3029                (13_021_612_539_908_538_853, 9),  // 133
3030                (13_929_745_610_903_012_864, 9),  // 134
3031                (14_893_745_087_865_234_375, 9),  // 135
3032                (15_916_595_351_771_938_816, 9),  // 136
3033                (17_001_416_405_572_203_977, 9),  // 137
3034                (18_151_468_971_815_029_248, 9),  // 138
3035                (139_353_667_211_683_681, 8),     // 139
3036                (147_578_905_600_000_000, 8),     // 140
3037                (156_225_851_787_813_921, 8),     // 141
3038                (165_312_903_998_914_816, 8),     // 142
3039                (174_859_124_550_883_201, 8),     // 143
3040                (184_884_258_895_036_416, 8),     // 144
3041                (195_408_755_062_890_625, 8),     // 145
3042                (206_453_783_524_884_736, 8),     // 146
3043                (218_041_257_467_152_161, 8),     // 147
3044                (230_193_853_492_166_656, 8),     // 148
3045                (242_935_032_749_128_801, 8),     // 149
3046                (256_289_062_500_000_000, 8),     // 150
3047                (270_281_038_127_131_201, 8),     // 151
3048                (284_936_905_588_473_856, 8),     // 152
3049                (300_283_484_326_400_961, 8),     // 153
3050                (316_348_490_636_206_336, 8),     // 154
3051                (333_160_561_500_390_625, 8),     // 155
3052                (350_749_278_894_882_816, 8),     // 156
3053                (369_145_194_573_386_401, 8),     // 157
3054                (388_379_855_336_079_616, 8),     // 158
3055                (408_485_828_788_939_521, 8),     // 159
3056                (429_496_729_600_000_000, 8),     // 160
3057                (451_447_246_258_894_081, 8),     // 161
3058                (474_373_168_346_071_296, 8),     // 162
3059                (498_311_414_318_121_121, 8),     // 163
3060                (523_300_059_815_673_856, 8),     // 164
3061                (549_378_366_500_390_625, 8),     // 165
3062                (576_586_811_427_594_496, 8),     // 166
3063                (604_967_116_961_135_041, 8),     // 167
3064                (634_562_281_237_118_976, 8),     // 168
3065                (665_416_609_183_179_841, 8),     // 169
3066                (697_575_744_100_000_000, 8),     // 170
3067                (731_086_699_811_838_561, 8),     // 171
3068                (765_997_893_392_859_136, 8),     // 172
3069                (802_359_178_476_091_681, 8),     // 173
3070                (840_221_879_151_902_976, 8),     // 174
3071                (879_638_824_462_890_625, 8),     // 175
3072                (920_664_383_502_155_776, 8),     // 176
3073                (963_354_501_121_950_081, 8),     // 177
3074                (1_007_766_734_259_732_736, 8),   // 178
3075                (1_053_960_288_888_713_761, 8),   // 179
3076                (1_101_996_057_600_000_000, 8),   // 180
3077                (1_151_936_657_823_500_641, 8),   // 181
3078                (1_203_846_470_694_789_376, 8),   // 182
3079                (1_257_791_680_575_160_641, 8),   // 183
3080                (1_313_840_315_232_157_696, 8),   // 184
3081                (1_372_062_286_687_890_625, 8),   // 185
3082                (1_432_529_432_742_502_656, 8),   // 186
3083                (1_495_315_559_180_183_521, 8),   // 187
3084                (1_560_496_482_665_168_896, 8),   // 188
3085                (1_628_150_074_335_205_281, 8),   // 189
3086                (1_698_356_304_100_000_000, 8),   // 190
3087                (1_771_197_285_652_216_321, 8),   // 191
3088                (1_846_757_322_198_614_016, 8),   // 192
3089                (1_925_122_952_918_976_001, 8),   // 193
3090                (2_006_383_000_160_502_016, 8),   // 194
3091                (2_090_628_617_375_390_625, 8),   // 195
3092                (2_177_953_337_809_371_136, 8),   // 196
3093                (2_268_453_123_948_987_361, 8),   // 197
3094                (2_362_226_417_735_475_456, 8),   // 198
3095                (2_459_374_191_553_118_401, 8),   // 199
3096                (2_560_000_000_000_000_000, 8),   // 200
3097                (2_664_210_032_449_121_601, 8),   // 201
3098                (2_772_113_166_407_885_056, 8),   // 202
3099                (2_883_821_021_683_985_761, 8),   // 203
3100                (2_999_448_015_365_799_936, 8),   // 204
3101                (3_119_111_417_625_390_625, 8),   // 205
3102                (3_242_931_408_352_297_216, 8),   // 206
3103                (3_371_031_134_626_313_601, 8),   // 207
3104                (3_503_536_769_037_500_416, 8),   // 208
3105                (3_640_577_568_861_717_121, 8),   // 209
3106                (3_782_285_936_100_000_000, 8),   // 210
3107                (3_928_797_478_390_152_481, 8),   // 211
3108                (4_080_251_070_798_954_496, 8),   // 212
3109                (4_236_788_918_503_437_921, 8),   // 213
3110                (4_398_556_620_369_715_456, 8),   // 214
3111                (4_565_703_233_437_890_625, 8),   // 215
3112                (4_738_381_338_321_616_896, 8),   // 216
3113                (4_916_747_105_530_914_241, 8),   // 217
3114                (5_100_960_362_726_891_776, 8),   // 218
3115                (5_291_184_662_917_065_441, 8),   // 219
3116                (5_487_587_353_600_000_000, 8),   // 220
3117                (5_690_339_646_868_044_961, 8),   // 221
3118                (5_899_616_690_476_974_336, 8),   // 222
3119                (6_115_597_639_891_380_481, 8),   // 223
3120                (6_338_465_731_314_712_576, 8),   // 224
3121                (6_568_408_355_712_890_625, 8),   // 225
3122                (6_805_617_133_840_466_176, 8),   // 226
3123                (7_050_287_992_278_341_281, 8),   // 227
3124                (7_302_621_240_492_097_536, 8),   // 228
3125                (7_562_821_648_920_027_361, 8),   // 229
3126                (7_831_098_528_100_000_000, 8),   // 230
3127                (8_107_665_808_844_335_041, 8),   // 231
3128                (8_392_742_123_471_896_576, 8),   // 232
3129                (8_686_550_888_106_661_441, 8),   // 233
3130                (8_989_320_386_052_055_296, 8),   // 234
3131                (9_301_283_852_250_390_625, 8),   // 235
3132                (9_622_679_558_836_781_056, 8),   // 236
3133                (9_953_750_901_796_946_721, 8),   // 237
3134                (10_294_746_488_738_365_696, 8),  // 238
3135                (10_645_920_227_784_266_881, 8),  // 239
3136                (11_007_531_417_600_000_000, 8),  // 240
3137                (11_379_844_838_561_358_721, 8),  // 241
3138                (11_763_130_845_074_473_216, 8),  // 242
3139                (12_157_665_459_056_928_801, 8),  // 243
3140                (12_563_730_464_589_807_616, 8),  // 244
3141                (12_981_613_503_750_390_625, 8),  // 245
3142                (13_411_608_173_635_297_536, 8),  // 246
3143                (13_854_014_124_583_882_561, 8),  // 247
3144                (14_309_137_159_611_744_256, 8),  // 248
3145                (14_777_289_335_064_248_001, 8),  // 249
3146                (15_258_789_062_500_000_000, 8),  // 250
3147                (15_753_961_211_814_252_001, 8),  // 251
3148                (16_263_137_215_612_256_256, 8),  // 252
3149                (16_786_655_174_842_630_561, 8),  // 253
3150                (17_324_859_965_700_833_536, 8),  // 254
3151                (17_878_103_347_812_890_625, 8),  // 255
3152                (72_057_594_037_927_936, 7),      // 256
3153            ];
3154
3155            let (base, power) = BASES[radix as usize];
3156            (base as BigDigit, power)
3157        }
3158        _ => panic!("Invalid bigdigit size"),
3159    }
3160}
3161
3162#[cfg(not(feature = "u64_digit"))]
3163#[test]
3164fn test_from_slice() {
3165    fn check(slice: &[u32], data: &[BigDigit]) {
3166        assert_eq!(&BigUint::from_slice(slice).data[..], data);
3167    }
3168    check(&[1], &[1]);
3169    check(&[0, 0, 0], &[]);
3170    check(&[1, 2, 0, 0], &[1, 2]);
3171    check(&[0, 0, 1, 2], &[0, 0, 1, 2]);
3172    check(&[0, 0, 1, 2, 0, 0], &[0, 0, 1, 2]);
3173    check(&[-1i32 as u32], &[-1i32 as BigDigit]);
3174}
3175
3176#[cfg(feature = "u64_digit")]
3177#[test]
3178fn test_from_slice() {
3179    fn check(slice: &[u32], data: &[BigDigit]) {
3180        assert_eq!(
3181            &BigUint::from_slice(slice).data[..],
3182            data,
3183            "from {:?}, to {:?}",
3184            slice,
3185            data
3186        );
3187    }
3188    check(&[1], &[1]);
3189    check(&[0, 0, 0], &[]);
3190    check(&[1, 2], &[8_589_934_593]);
3191    check(&[1, 2, 0, 0], &[8_589_934_593]);
3192    check(&[0, 0, 1, 2], &[0, 8_589_934_593]);
3193    check(&[0, 0, 1, 2, 0, 0], &[0, 8_589_934_593]);
3194    check(&[-1i32 as u32], &[(-1i32 as u32) as BigDigit]);
3195}
3196
3197#[test]
3198fn test_from_slice_native() {
3199    fn check(slice: &[BigDigit], data: &[BigDigit]) {
3200        assert!(&BigUint::from_slice_native(slice).data[..] == data);
3201    }
3202    check(&[1], &[1]);
3203    check(&[0, 0, 0], &[]);
3204    check(&[1, 2, 0, 0], &[1, 2]);
3205    check(&[0, 0, 1, 2], &[0, 0, 1, 2]);
3206    check(&[0, 0, 1, 2, 0, 0], &[0, 0, 1, 2]);
3207    check(&[-1i32 as BigDigit], &[-1i32 as BigDigit]);
3208}
3209
3210#[test]
3211fn test_assign_from_slice_native() {
3212    fn check(slice: &[BigDigit], data: &[BigDigit]) {
3213        let mut p = BigUint::from_slice_native(&[2627, 0, 9182, 42]);
3214        p.assign_from_slice_native(slice);
3215        assert!(&p.data[..] == data);
3216    }
3217    check(&[1], &[1]);
3218    check(&[0, 0, 0], &[]);
3219    check(&[1, 2, 0, 0], &[1, 2]);
3220    check(&[0, 0, 1, 2], &[0, 0, 1, 2]);
3221    check(&[0, 0, 1, 2, 0, 0], &[0, 0, 1, 2]);
3222    check(&[-1i32 as BigDigit], &[-1i32 as BigDigit]);
3223}
3224
3225#[cfg(has_i128)]
3226#[test]
3227fn test_u32_u128() {
3228    assert_eq!(u32_from_u128(0u128), (0, 0, 0, 0));
3229    assert_eq!(
3230        u32_from_u128(u128::max_value()),
3231        (
3232            u32::max_value(),
3233            u32::max_value(),
3234            u32::max_value(),
3235            u32::max_value()
3236        )
3237    );
3238
3239    assert_eq!(
3240        u32_from_u128(u32::max_value() as u128),
3241        (0, 0, 0, u32::max_value())
3242    );
3243
3244    assert_eq!(
3245        u32_from_u128(u64::max_value() as u128),
3246        (0, 0, u32::max_value(), u32::max_value())
3247    );
3248
3249    assert_eq!(
3250        u32_from_u128((u64::max_value() as u128) + u32::max_value() as u128),
3251        (0, 1, 0, u32::max_value() - 1)
3252    );
3253
3254    assert_eq!(u32_from_u128(36_893_488_151_714_070_528), (0, 2, 1, 0));
3255}
3256
3257#[cfg(has_i128)]
3258#[test]
3259fn test_u128_u32_roundtrip() {
3260    // roundtrips
3261    let values = vec![
3262        0u128,
3263        1u128,
3264        u64::max_value() as u128 * 3,
3265        u32::max_value() as u128,
3266        u64::max_value() as u128,
3267        (u64::max_value() as u128) + u32::max_value() as u128,
3268        u128::max_value(),
3269    ];
3270
3271    for val in &values {
3272        let (a, b, c, d) = u32_from_u128(*val);
3273        assert_eq!(u32_to_u128(a, b, c, d), *val);
3274    }
3275}
3276
3277// Mod Inverse
3278
3279impl<'a> ModInverse<&'a BigUint> for BigUint {
3280    type Output = BigInt;
3281    fn mod_inverse(self, m: &'a BigUint) -> Option<BigInt> {
3282        mod_inverse(Cow::Owned(self), Cow::Borrowed(m))
3283    }
3284}
3285
3286impl ModInverse<BigUint> for BigUint {
3287    type Output = BigInt;
3288    fn mod_inverse(self, m: BigUint) -> Option<BigInt> {
3289        mod_inverse(Cow::Owned(self), Cow::Owned(m))
3290    }
3291}
3292
3293impl<'a> ModInverse<&'a BigInt> for BigUint {
3294    type Output = BigInt;
3295    fn mod_inverse(self, m: &'a BigInt) -> Option<BigInt> {
3296        mod_inverse(Cow::Owned(self), Cow::Owned(m.to_biguint().unwrap()))
3297    }
3298}
3299impl ModInverse<BigInt> for BigUint {
3300    type Output = BigInt;
3301    fn mod_inverse(self, m: BigInt) -> Option<BigInt> {
3302        mod_inverse(Cow::Owned(self), Cow::Owned(m.into_biguint().unwrap()))
3303    }
3304}
3305
3306impl<'a, 'b> ModInverse<&'b BigUint> for &'a BigUint {
3307    type Output = BigInt;
3308
3309    fn mod_inverse(self, m: &'b BigUint) -> Option<BigInt> {
3310        mod_inverse(Cow::Borrowed(self), Cow::Borrowed(m))
3311    }
3312}
3313
3314impl<'a> ModInverse<BigUint> for &'a BigUint {
3315    type Output = BigInt;
3316
3317    fn mod_inverse(self, m: BigUint) -> Option<BigInt> {
3318        mod_inverse(Cow::Borrowed(self), Cow::Owned(m))
3319    }
3320}
3321
3322impl<'a, 'b> ModInverse<&'b BigInt> for &'a BigUint {
3323    type Output = BigInt;
3324
3325    fn mod_inverse(self, m: &'b BigInt) -> Option<BigInt> {
3326        mod_inverse(Cow::Borrowed(self), Cow::Owned(m.to_biguint().unwrap()))
3327    }
3328}
3329
3330// Extended GCD
3331
3332impl<'a> ExtendedGcd<&'a BigUint> for BigUint {
3333    fn extended_gcd(self, other: &'a BigUint) -> (BigInt, BigInt, BigInt) {
3334        let (a, b, c) = extended_gcd(Cow::Owned(self), Cow::Borrowed(other), true);
3335        (a, b.unwrap(), c.unwrap())
3336    }
3337}
3338
3339impl<'a> ExtendedGcd<&'a BigInt> for BigUint {
3340    fn extended_gcd(self, other: &'a BigInt) -> (BigInt, BigInt, BigInt) {
3341        let (a, b, c) = extended_gcd(
3342            Cow::Owned(self),
3343            Cow::Owned(other.to_biguint().unwrap()),
3344            true,
3345        );
3346        (a, b.unwrap(), c.unwrap())
3347    }
3348}
3349
3350impl<'a, 'b> ExtendedGcd<&'b BigInt> for &'a BigUint {
3351    fn extended_gcd(self, other: &'b BigInt) -> (BigInt, BigInt, BigInt) {
3352        let (a, b, c) = extended_gcd(
3353            Cow::Borrowed(self),
3354            Cow::Owned(other.to_biguint().unwrap()),
3355            true,
3356        );
3357        (a, b.unwrap(), c.unwrap())
3358    }
3359}
3360
3361impl<'a, 'b> ExtendedGcd<&'b BigUint> for &'a BigUint {
3362    fn extended_gcd(self, other: &'b BigUint) -> (BigInt, BigInt, BigInt) {
3363        let (a, b, c) = extended_gcd(Cow::Borrowed(self), Cow::Borrowed(other), true);
3364        (a, b.unwrap(), c.unwrap())
3365    }
3366}
3367
3368#[test]
3369fn test_set_digit() {
3370    let mut a = BigUint::new(vec![3]);
3371    a.set_digit(4);
3372    assert_eq!(a.data.len(), 1);
3373    assert_eq!(a.data[0], 4);
3374
3375    let mut a = BigUint::new(vec![3, 2]);
3376    a.set_digit(4);
3377    assert_eq!(a.data.len(), 1);
3378    assert_eq!(a.data[0], 4);
3379
3380    let mut a = BigUint::new(vec![]);
3381    a.set_digit(4);
3382    assert_eq!(a.data.len(), 1);
3383    assert_eq!(a.data[0], 4);
3384}
3385
3386// arbitrary support
3387#[cfg(feature = "fuzz")]
3388impl arbitrary::Arbitrary<'_> for BigUint {
3389    fn arbitrary(src: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
3390        let data = SmallVec::arbitrary(src)?;
3391        Ok(Self { data })
3392    }
3393
3394    fn size_hint(depth: usize) -> (usize, Option<usize>) {
3395        SmallVec::<[BigDigit; VEC_SIZE]>::size_hint(depth)
3396    }
3397}