1use crate::big_digit::{self, BigDigit};
2use crate::std_alloc::{String, Vec};
3
4use core::cmp;
5use core::cmp::Ordering;
6use core::default::Default;
7use core::fmt;
8use core::hash;
9use core::mem;
10use core::str;
11use core::{u32, u64, u8};
12
13use num_integer::{Integer, Roots};
14use num_traits::{Num, One, Pow, ToPrimitive, Unsigned, Zero};
15
16mod addition;
17mod division;
18mod multiplication;
19mod subtraction;
20
21mod bits;
22mod convert;
23mod iter;
24mod monty;
25mod power;
26mod shift;
27
28#[cfg(any(feature = "quickcheck", feature = "arbitrary"))]
29mod arbitrary;
30
31#[cfg(feature = "serde")]
32mod serde;
33
34pub(crate) use self::convert::to_str_radix_reversed;
35pub use self::iter::{U32Digits, U64Digits};
36
37pub struct BigUint {
39 data: Vec<BigDigit>,
40}
41
42impl Clone for BigUint {
45 #[inline]
46 fn clone(&self) -> Self {
47 BigUint {
48 data: self.data.clone(),
49 }
50 }
51
52 #[inline]
53 fn clone_from(&mut self, other: &Self) {
54 self.data.clone_from(&other.data);
55 }
56}
57
58impl hash::Hash for BigUint {
59 #[inline]
60 fn hash<H: hash::Hasher>(&self, state: &mut H) {
61 debug_assert!(self.data.last() != Some(&0));
62 self.data.hash(state);
63 }
64}
65
66impl PartialEq for BigUint {
67 #[inline]
68 fn eq(&self, other: &BigUint) -> bool {
69 debug_assert!(self.data.last() != Some(&0));
70 debug_assert!(other.data.last() != Some(&0));
71 self.data == other.data
72 }
73}
74impl Eq for BigUint {}
75
76impl PartialOrd for BigUint {
77 #[inline]
78 fn partial_cmp(&self, other: &BigUint) -> Option<Ordering> {
79 Some(self.cmp(other))
80 }
81}
82
83impl Ord for BigUint {
84 #[inline]
85 fn cmp(&self, other: &BigUint) -> Ordering {
86 cmp_slice(&self.data[..], &other.data[..])
87 }
88}
89
90#[inline]
91fn cmp_slice(a: &[BigDigit], b: &[BigDigit]) -> Ordering {
92 debug_assert!(a.last() != Some(&0));
93 debug_assert!(b.last() != Some(&0));
94
95 match Ord::cmp(&a.len(), &b.len()) {
96 Ordering::Equal => Iterator::cmp(a.iter().rev(), b.iter().rev()),
97 other => other,
98 }
99}
100
101impl Default for BigUint {
102 #[inline]
103 fn default() -> BigUint {
104 Zero::zero()
105 }
106}
107
108impl fmt::Debug for BigUint {
109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110 fmt::Display::fmt(self, f)
111 }
112}
113
114impl fmt::Display for BigUint {
115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116 f.pad_integral(true, "", &self.to_str_radix(10))
117 }
118}
119
120impl fmt::LowerHex for BigUint {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 f.pad_integral(true, "0x", &self.to_str_radix(16))
123 }
124}
125
126impl fmt::UpperHex for BigUint {
127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128 let mut s = self.to_str_radix(16);
129 s.make_ascii_uppercase();
130 f.pad_integral(true, "0x", &s)
131 }
132}
133
134impl fmt::Binary for BigUint {
135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136 f.pad_integral(true, "0b", &self.to_str_radix(2))
137 }
138}
139
140impl fmt::Octal for BigUint {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 f.pad_integral(true, "0o", &self.to_str_radix(8))
143 }
144}
145
146impl Zero for BigUint {
147 #[inline]
148 fn zero() -> BigUint {
149 BigUint { data: Vec::new() }
150 }
151
152 #[inline]
153 fn set_zero(&mut self) {
154 self.data.clear();
155 }
156
157 #[inline]
158 fn is_zero(&self) -> bool {
159 self.data.is_empty()
160 }
161}
162
163impl One for BigUint {
164 #[inline]
165 fn one() -> BigUint {
166 BigUint { data: vec![1] }
167 }
168
169 #[inline]
170 fn set_one(&mut self) {
171 self.data.clear();
172 self.data.push(1);
173 }
174
175 #[inline]
176 fn is_one(&self) -> bool {
177 self.data[..] == [1]
178 }
179}
180
181impl Unsigned for BigUint {}
182
183impl Integer for BigUint {
184 #[inline]
185 fn div_rem(&self, other: &BigUint) -> (BigUint, BigUint) {
186 division::div_rem_ref(self, other)
187 }
188
189 #[inline]
190 fn div_floor(&self, other: &BigUint) -> BigUint {
191 let (d, _) = division::div_rem_ref(self, other);
192 d
193 }
194
195 #[inline]
196 fn mod_floor(&self, other: &BigUint) -> BigUint {
197 let (_, m) = division::div_rem_ref(self, other);
198 m
199 }
200
201 #[inline]
202 fn div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint) {
203 division::div_rem_ref(self, other)
204 }
205
206 #[inline]
207 fn div_ceil(&self, other: &BigUint) -> BigUint {
208 let (d, m) = division::div_rem_ref(self, other);
209 if m.is_zero() {
210 d
211 } else {
212 d + 1u32
213 }
214 }
215
216 #[inline]
220 fn gcd(&self, other: &Self) -> Self {
221 #[inline]
222 fn twos(x: &BigUint) -> u64 {
223 x.trailing_zeros().unwrap_or(0)
224 }
225
226 if self.is_zero() {
228 return other.clone();
229 }
230 if other.is_zero() {
231 return self.clone();
232 }
233 let mut m = self.clone();
234 let mut n = other.clone();
235
236 let shift = cmp::min(twos(&n), twos(&m));
238
239 n >>= twos(&n);
242
243 while !m.is_zero() {
244 m >>= twos(&m);
245 if n > m {
246 mem::swap(&mut n, &mut m)
247 }
248 m -= &n;
249 }
250
251 n << shift
252 }
253
254 #[inline]
256 fn lcm(&self, other: &BigUint) -> BigUint {
257 if self.is_zero() && other.is_zero() {
258 Self::zero()
259 } else {
260 self / self.gcd(other) * other
261 }
262 }
263
264 #[inline]
267 fn gcd_lcm(&self, other: &Self) -> (Self, Self) {
268 let gcd = self.gcd(other);
269 let lcm = if gcd.is_zero() {
270 Self::zero()
271 } else {
272 self / &gcd * other
273 };
274 (gcd, lcm)
275 }
276
277 #[inline]
279 fn divides(&self, other: &BigUint) -> bool {
280 self.is_multiple_of(other)
281 }
282
283 #[inline]
285 fn is_multiple_of(&self, other: &BigUint) -> bool {
286 (self % other).is_zero()
287 }
288
289 #[inline]
291 fn is_even(&self) -> bool {
292 match self.data.first() {
294 Some(x) => x.is_even(),
295 None => true,
296 }
297 }
298
299 #[inline]
301 fn is_odd(&self) -> bool {
302 !self.is_even()
303 }
304
305 #[inline]
307 fn next_multiple_of(&self, other: &Self) -> Self {
308 let m = self.mod_floor(other);
309 if m.is_zero() {
310 self.clone()
311 } else {
312 self + (other - m)
313 }
314 }
315 #[inline]
317 fn prev_multiple_of(&self, other: &Self) -> Self {
318 self - self.mod_floor(other)
319 }
320}
321
322#[inline]
323fn fixpoint<F>(mut x: BigUint, max_bits: u64, f: F) -> BigUint
324where
325 F: Fn(&BigUint) -> BigUint,
326{
327 let mut xn = f(&x);
328
329 while x < xn {
332 x = if xn.bits() > max_bits {
336 BigUint::one() << max_bits
337 } else {
338 xn
339 };
340 xn = f(&x);
341 }
342
343 while x > xn {
345 x = xn;
346 xn = f(&x);
347 }
348 x
349}
350
351impl Roots for BigUint {
352 fn nth_root(&self, n: u32) -> Self {
358 assert!(n > 0, "root degree n must be at least 1");
359
360 if self.is_zero() || self.is_one() {
361 return self.clone();
362 }
363
364 match n {
365 1 => return self.clone(),
367 2 => return self.sqrt(),
368 3 => return self.cbrt(),
369 _ => (),
370 }
371
372 let bits = self.bits();
374 let n64 = u64::from(n);
375 if bits <= n64 {
376 return BigUint::one();
377 }
378
379 if let Some(x) = self.to_u64() {
381 return x.nth_root(n).into();
382 }
383
384 let max_bits = bits / n64 + 1;
385
386 #[cfg(feature = "std")]
387 let guess = match self.to_f64() {
388 Some(f) if f.is_finite() => {
389 use num_traits::FromPrimitive;
390
391 BigUint::from_f64((f.ln() / f64::from(n)).exp()).unwrap()
393 }
394 _ => {
395 let extra_bits = bits - (core::f64::MAX_EXP as u64 - 1);
398 let root_scale = Integer::div_ceil(&extra_bits, &n64);
399 let scale = root_scale * n64;
400 if scale < bits && bits - scale > n64 {
401 (self >> scale).nth_root(n) << root_scale
402 } else {
403 BigUint::one() << max_bits
404 }
405 }
406 };
407
408 #[cfg(not(feature = "std"))]
409 let guess = BigUint::one() << max_bits;
410
411 let n_min_1 = n - 1;
412 fixpoint(guess, max_bits, move |s| {
413 let q = self / s.pow(n_min_1);
414 let t = n_min_1 * s + q;
415 t / n
416 })
417 }
418
419 fn sqrt(&self) -> Self {
422 if self.is_zero() || self.is_one() {
423 return self.clone();
424 }
425
426 if let Some(x) = self.to_u64() {
428 return x.sqrt().into();
429 }
430
431 let bits = self.bits();
432 let max_bits = bits / 2 + 1;
433
434 #[cfg(feature = "std")]
435 let guess = match self.to_f64() {
436 Some(f) if f.is_finite() => {
437 use num_traits::FromPrimitive;
438
439 BigUint::from_f64(f.sqrt()).unwrap()
441 }
442 _ => {
443 let extra_bits = bits - (core::f64::MAX_EXP as u64 - 1);
446 let root_scale = (extra_bits + 1) / 2;
447 let scale = root_scale * 2;
448 (self >> scale).sqrt() << root_scale
449 }
450 };
451
452 #[cfg(not(feature = "std"))]
453 let guess = BigUint::one() << max_bits;
454
455 fixpoint(guess, max_bits, move |s| {
456 let q = self / s;
457 let t = s + q;
458 t >> 1
459 })
460 }
461
462 fn cbrt(&self) -> Self {
463 if self.is_zero() || self.is_one() {
464 return self.clone();
465 }
466
467 if let Some(x) = self.to_u64() {
469 return x.cbrt().into();
470 }
471
472 let bits = self.bits();
473 let max_bits = bits / 3 + 1;
474
475 #[cfg(feature = "std")]
476 let guess = match self.to_f64() {
477 Some(f) if f.is_finite() => {
478 use num_traits::FromPrimitive;
479
480 BigUint::from_f64(f.cbrt()).unwrap()
482 }
483 _ => {
484 let extra_bits = bits - (core::f64::MAX_EXP as u64 - 1);
487 let root_scale = (extra_bits + 2) / 3;
488 let scale = root_scale * 3;
489 (self >> scale).cbrt() << root_scale
490 }
491 };
492
493 #[cfg(not(feature = "std"))]
494 let guess = BigUint::one() << max_bits;
495
496 fixpoint(guess, max_bits, move |s| {
497 let q = self / (s * s);
498 let t = (s << 1) + q;
499 t / 3u32
500 })
501 }
502}
503
504pub trait ToBigUint {
506 fn to_biguint(&self) -> Option<BigUint>;
508}
509
510#[inline]
514pub(crate) fn biguint_from_vec(digits: Vec<BigDigit>) -> BigUint {
515 BigUint { data: digits }.normalized()
516}
517
518impl BigUint {
519 #[inline]
523 pub fn new(digits: Vec<u32>) -> BigUint {
524 let mut big = BigUint::zero();
525
526 #[cfg(not(u64_digit))]
527 {
528 big.data = digits;
529 big.normalize();
530 }
531
532 #[cfg(u64_digit)]
533 big.assign_from_slice(&digits);
534
535 big
536 }
537
538 #[inline]
542 pub fn from_slice(slice: &[u32]) -> BigUint {
543 let mut big = BigUint::zero();
544 big.assign_from_slice(slice);
545 big
546 }
547
548 #[inline]
552 pub fn assign_from_slice(&mut self, slice: &[u32]) {
553 self.data.clear();
554
555 #[cfg(not(u64_digit))]
556 self.data.extend_from_slice(slice);
557
558 #[cfg(u64_digit)]
559 self.data.extend(slice.chunks(2).map(u32_chunk_to_u64));
560
561 self.normalize();
562 }
563
564 #[inline]
583 pub fn from_bytes_be(bytes: &[u8]) -> BigUint {
584 if bytes.is_empty() {
585 Zero::zero()
586 } else {
587 let mut v = bytes.to_vec();
588 v.reverse();
589 BigUint::from_bytes_le(&*v)
590 }
591 }
592
593 #[inline]
597 pub fn from_bytes_le(bytes: &[u8]) -> BigUint {
598 if bytes.is_empty() {
599 Zero::zero()
600 } else {
601 convert::from_bitwise_digits_le(bytes, 8)
602 }
603 }
604
605 #[inline]
622 pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigUint> {
623 let s = str::from_utf8(buf).ok()?;
624 BigUint::from_str_radix(s, radix).ok()
625 }
626
627 pub fn from_radix_be(buf: &[u8], radix: u32) -> Option<BigUint> {
644 convert::from_radix_be(buf, radix)
645 }
646
647 pub fn from_radix_le(buf: &[u8], radix: u32) -> Option<BigUint> {
664 convert::from_radix_le(buf, radix)
665 }
666
667 #[inline]
678 pub fn to_bytes_be(&self) -> Vec<u8> {
679 let mut v = self.to_bytes_le();
680 v.reverse();
681 v
682 }
683
684 #[inline]
695 pub fn to_bytes_le(&self) -> Vec<u8> {
696 if self.is_zero() {
697 vec![0]
698 } else {
699 convert::to_bitwise_digits_le(self, 8)
700 }
701 }
702
703 #[inline]
717 pub fn to_u32_digits(&self) -> Vec<u32> {
718 self.iter_u32_digits().collect()
719 }
720
721 #[inline]
736 pub fn to_u64_digits(&self) -> Vec<u64> {
737 self.iter_u64_digits().collect()
738 }
739
740 #[inline]
754 pub fn iter_u32_digits(&self) -> U32Digits<'_> {
755 U32Digits::new(self.data.as_slice())
756 }
757
758 #[inline]
773 pub fn iter_u64_digits(&self) -> U64Digits<'_> {
774 U64Digits::new(self.data.as_slice())
775 }
776
777 #[inline]
789 pub fn to_str_radix(&self, radix: u32) -> String {
790 let mut v = to_str_radix_reversed(self, radix);
791 v.reverse();
792 unsafe { String::from_utf8_unchecked(v) }
793 }
794
795 #[inline]
810 pub fn to_radix_be(&self, radix: u32) -> Vec<u8> {
811 let mut v = convert::to_radix_le(self, radix);
812 v.reverse();
813 v
814 }
815
816 #[inline]
831 pub fn to_radix_le(&self, radix: u32) -> Vec<u8> {
832 convert::to_radix_le(self, radix)
833 }
834
835 #[inline]
837 pub fn bits(&self) -> u64 {
838 if self.is_zero() {
839 return 0;
840 }
841 let zeros: u64 = self.data.last().unwrap().leading_zeros().into();
842 self.data.len() as u64 * u64::from(big_digit::BITS) - zeros
843 }
844
845 #[inline]
848 fn normalize(&mut self) {
849 if let Some(&0) = self.data.last() {
850 let len = self.data.iter().rposition(|&d| d != 0).map_or(0, |i| i + 1);
851 self.data.truncate(len);
852 }
853 if self.data.len() < self.data.capacity() / 4 {
854 self.data.shrink_to_fit();
855 }
856 }
857
858 #[inline]
860 fn normalized(mut self) -> BigUint {
861 self.normalize();
862 self
863 }
864
865 pub fn pow(&self, exponent: u32) -> Self {
867 Pow::pow(self, exponent)
868 }
869
870 pub fn modpow(&self, exponent: &Self, modulus: &Self) -> Self {
874 power::modpow(self, exponent, modulus)
875 }
876
877 pub fn sqrt(&self) -> Self {
880 Roots::sqrt(self)
881 }
882
883 pub fn cbrt(&self) -> Self {
886 Roots::cbrt(self)
887 }
888
889 pub fn nth_root(&self, n: u32) -> Self {
892 Roots::nth_root(self, n)
893 }
894
895 pub fn trailing_zeros(&self) -> Option<u64> {
898 let i = self.data.iter().position(|&digit| digit != 0)?;
899 let zeros: u64 = self.data[i].trailing_zeros().into();
900 Some(i as u64 * u64::from(big_digit::BITS) + zeros)
901 }
902
903 pub fn trailing_ones(&self) -> u64 {
905 if let Some(i) = self.data.iter().position(|&digit| !digit != 0) {
906 let ones: u64 = (!self.data[i]).trailing_zeros().into();
910 i as u64 * u64::from(big_digit::BITS) + ones
911 } else {
912 self.data.len() as u64 * u64::from(big_digit::BITS)
913 }
914 }
915
916 pub fn count_ones(&self) -> u64 {
918 self.data.iter().map(|&d| u64::from(d.count_ones())).sum()
919 }
920
921 pub fn bit(&self, bit: u64) -> bool {
923 let bits_per_digit = u64::from(big_digit::BITS);
924 if let Some(digit_index) = (bit / bits_per_digit).to_usize() {
925 if let Some(digit) = self.data.get(digit_index) {
926 let bit_mask = (1 as BigDigit) << (bit % bits_per_digit);
927 return (digit & bit_mask) != 0;
928 }
929 }
930 false
931 }
932
933 pub fn set_bit(&mut self, bit: u64, value: bool) {
938 let bits_per_digit = u64::from(big_digit::BITS);
941 let digit_index = (bit / bits_per_digit)
942 .to_usize()
943 .unwrap_or(core::usize::MAX);
944 let bit_mask = (1 as BigDigit) << (bit % bits_per_digit);
945 if value {
946 if digit_index >= self.data.len() {
947 let new_len = digit_index.saturating_add(1);
948 self.data.resize(new_len, 0);
949 }
950 self.data[digit_index] |= bit_mask;
951 } else if digit_index < self.data.len() {
952 self.data[digit_index] &= !bit_mask;
953 self.normalize();
955 }
956 }
957}
958
959pub(crate) trait IntDigits {
960 fn digits(&self) -> &[BigDigit];
961 fn digits_mut(&mut self) -> &mut Vec<BigDigit>;
962 fn normalize(&mut self);
963 fn capacity(&self) -> usize;
964 fn len(&self) -> usize;
965}
966
967impl IntDigits for BigUint {
968 #[inline]
969 fn digits(&self) -> &[BigDigit] {
970 &self.data
971 }
972 #[inline]
973 fn digits_mut(&mut self) -> &mut Vec<BigDigit> {
974 &mut self.data
975 }
976 #[inline]
977 fn normalize(&mut self) {
978 self.normalize();
979 }
980 #[inline]
981 fn capacity(&self) -> usize {
982 self.data.capacity()
983 }
984 #[inline]
985 fn len(&self) -> usize {
986 self.data.len()
987 }
988}
989
990#[inline]
992fn u32_chunk_to_u64(chunk: &[u32]) -> u64 {
993 let mut digit = chunk[0] as u64;
995 if let Some(&hi) = chunk.get(1) {
996 digit |= (hi as u64) << 32;
997 }
998 digit
999}
1000
1001#[cfg(any(test, not(u64_digit)))]
1003#[inline]
1004fn u32_to_u128(a: u32, b: u32, c: u32, d: u32) -> u128 {
1005 u128::from(d) | (u128::from(c) << 32) | (u128::from(b) << 64) | (u128::from(a) << 96)
1006}
1007
1008#[cfg(any(test, not(u64_digit)))]
1010#[inline]
1011fn u32_from_u128(n: u128) -> (u32, u32, u32, u32) {
1012 (
1013 (n >> 96) as u32,
1014 (n >> 64) as u32,
1015 (n >> 32) as u32,
1016 n as u32,
1017 )
1018}
1019
1020#[cfg(not(u64_digit))]
1021#[test]
1022fn test_from_slice() {
1023 fn check(slice: &[u32], data: &[BigDigit]) {
1024 assert_eq!(BigUint::from_slice(slice).data, data);
1025 }
1026 check(&[1], &[1]);
1027 check(&[0, 0, 0], &[]);
1028 check(&[1, 2, 0, 0], &[1, 2]);
1029 check(&[0, 0, 1, 2], &[0, 0, 1, 2]);
1030 check(&[0, 0, 1, 2, 0, 0], &[0, 0, 1, 2]);
1031 check(&[-1i32 as u32], &[-1i32 as BigDigit]);
1032}
1033
1034#[cfg(u64_digit)]
1035#[test]
1036fn test_from_slice() {
1037 fn check(slice: &[u32], data: &[BigDigit]) {
1038 assert_eq!(
1039 BigUint::from_slice(slice).data,
1040 data,
1041 "from {:?}, to {:?}",
1042 slice,
1043 data
1044 );
1045 }
1046 check(&[1], &[1]);
1047 check(&[0, 0, 0], &[]);
1048 check(&[1, 2], &[8_589_934_593]);
1049 check(&[1, 2, 0, 0], &[8_589_934_593]);
1050 check(&[0, 0, 1, 2], &[0, 8_589_934_593]);
1051 check(&[0, 0, 1, 2, 0, 0], &[0, 8_589_934_593]);
1052 check(&[-1i32 as u32], &[(-1i32 as u32) as BigDigit]);
1053}
1054
1055#[test]
1056fn test_u32_u128() {
1057 assert_eq!(u32_from_u128(0u128), (0, 0, 0, 0));
1058 assert_eq!(
1059 u32_from_u128(u128::max_value()),
1060 (
1061 u32::max_value(),
1062 u32::max_value(),
1063 u32::max_value(),
1064 u32::max_value()
1065 )
1066 );
1067
1068 assert_eq!(
1069 u32_from_u128(u32::max_value() as u128),
1070 (0, 0, 0, u32::max_value())
1071 );
1072
1073 assert_eq!(
1074 u32_from_u128(u64::max_value() as u128),
1075 (0, 0, u32::max_value(), u32::max_value())
1076 );
1077
1078 assert_eq!(
1079 u32_from_u128((u64::max_value() as u128) + u32::max_value() as u128),
1080 (0, 1, 0, u32::max_value() - 1)
1081 );
1082
1083 assert_eq!(u32_from_u128(36_893_488_151_714_070_528), (0, 2, 1, 0));
1084}
1085
1086#[test]
1087fn test_u128_u32_roundtrip() {
1088 let values = vec![
1090 0u128,
1091 1u128,
1092 u64::max_value() as u128 * 3,
1093 u32::max_value() as u128,
1094 u64::max_value() as u128,
1095 (u64::max_value() as u128) + u32::max_value() as u128,
1096 u128::max_value(),
1097 ];
1098
1099 for val in &values {
1100 let (a, b, c, d) = u32_from_u128(*val);
1101 assert_eq!(u32_to_u128(a, b, c, d), *val);
1102 }
1103}