1#![allow(clippy::suspicious_arithmetic_impl)]
3
4use alloc::string::String;
5use alloc::vec::Vec;
6use core::cmp::Ordering::{self, Equal};
7use core::default::Default;
8use core::fmt;
9use core::hash;
10use core::ops::{Neg, Not};
11use core::str;
12
13use num_integer::{Integer, Roots};
14use num_traits::{ConstZero, Num, One, Pow, Signed, Zero};
15
16use self::Sign::{Minus, NoSign, Plus};
17
18use crate::big_digit::BigDigit;
19use crate::biguint::to_str_radix_reversed;
20use crate::biguint::{BigUint, IntDigits, U32Digits, U64Digits};
21
22mod addition;
23mod division;
24mod multiplication;
25mod subtraction;
26
27mod arbitrary;
28mod bits;
29mod convert;
30mod power;
31mod serde;
32mod shift;
33
34)]
36pub enum Sign {
37 Minus,
38 NoSign,
39 Plus,
40}
41
42impl Neg for Sign {
43 type Output = Sign;
44
45 #[inline]
47 fn neg(self) -> Sign {
48 match self {
49 Minus => Plus,
50 NoSign => NoSign,
51 Plus => Minus,
52 }
53 }
54}
55
56pub struct BigInt {
58 sign: Sign,
59 data: BigUint,
60}
61
62impl Clone for BigInt {
65 #[inline]
66 fn clone(&self) -> Self {
67 BigInt {
68 sign: self.sign,
69 data: self.data.clone(),
70 }
71 }
72
73 #[inline]
74 fn clone_from(&mut self, other: &Self) {
75 self.sign = other.sign;
76 self.data.clone_from(&other.data);
77 }
78}
79
80impl hash::Hash for BigInt {
81 #[inline]
82 fn hash<H: hash::Hasher>(&self, state: &mut H) {
83 if true {
if !((self.sign != NoSign) ^ self.data.is_zero()) {
::core::panicking::panic("assertion failed: (self.sign != NoSign) ^ self.data.is_zero()")
};
};debug_assert!((self.sign != NoSign) ^ self.data.is_zero());
84 self.sign.hash(state);
85 if self.sign != NoSign {
86 self.data.hash(state);
87 }
88 }
89}
90
91impl PartialEq for BigInt {
92 #[inline]
93 fn eq(&self, other: &BigInt) -> bool {
94 if true {
if !((self.sign != NoSign) ^ self.data.is_zero()) {
::core::panicking::panic("assertion failed: (self.sign != NoSign) ^ self.data.is_zero()")
};
};debug_assert!((self.sign != NoSign) ^ self.data.is_zero());
95 if true {
if !((other.sign != NoSign) ^ other.data.is_zero()) {
::core::panicking::panic("assertion failed: (other.sign != NoSign) ^ other.data.is_zero()")
};
};debug_assert!((other.sign != NoSign) ^ other.data.is_zero());
96 self.sign == other.sign && (self.sign == NoSign || self.data == other.data)
97 }
98}
99
100impl Eq for BigInt {}
101
102impl PartialOrd for BigInt {
103 #[inline]
104 fn partial_cmp(&self, other: &BigInt) -> Option<Ordering> {
105 Some(self.cmp(other))
106 }
107}
108
109impl Ord for BigInt {
110 #[inline]
111 fn cmp(&self, other: &BigInt) -> Ordering {
112 if true {
if !((self.sign != NoSign) ^ self.data.is_zero()) {
::core::panicking::panic("assertion failed: (self.sign != NoSign) ^ self.data.is_zero()")
};
};debug_assert!((self.sign != NoSign) ^ self.data.is_zero());
113 if true {
if !((other.sign != NoSign) ^ other.data.is_zero()) {
::core::panicking::panic("assertion failed: (other.sign != NoSign) ^ other.data.is_zero()")
};
};debug_assert!((other.sign != NoSign) ^ other.data.is_zero());
114 let scmp = self.sign.cmp(&other.sign);
115 if scmp != Equal {
116 return scmp;
117 }
118
119 match self.sign {
120 NoSign => Equal,
121 Plus => self.data.cmp(&other.data),
122 Minus => other.data.cmp(&self.data),
123 }
124 }
125}
126
127impl Default for BigInt {
128 #[inline]
129 fn default() -> BigInt {
130 Self::ZERO
131 }
132}
133
134impl fmt::Debug for BigInt {
135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136 fmt::Display::fmt(self, f)
137 }
138}
139
140impl fmt::Display for BigInt {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 f.pad_integral(!self.is_negative(), "", &self.data.to_str_radix(10))
143 }
144}
145
146impl fmt::Binary for BigInt {
147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 f.pad_integral(!self.is_negative(), "0b", &self.data.to_str_radix(2))
149 }
150}
151
152impl fmt::Octal for BigInt {
153 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154 f.pad_integral(!self.is_negative(), "0o", &self.data.to_str_radix(8))
155 }
156}
157
158impl fmt::LowerHex for BigInt {
159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160 f.pad_integral(!self.is_negative(), "0x", &self.data.to_str_radix(16))
161 }
162}
163
164impl fmt::UpperHex for BigInt {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 let mut s = self.data.to_str_radix(16);
167 s.make_ascii_uppercase();
168 f.pad_integral(!self.is_negative(), "0x", &s)
169 }
170}
171
172impl Not for BigInt {
177 type Output = BigInt;
178
179 fn not(mut self) -> BigInt {
180 match self.sign {
181 NoSign | Plus => {
182 self.data += 1u32;
183 self.sign = Minus;
184 }
185 Minus => {
186 self.data -= 1u32;
187 self.sign = if self.data.is_zero() { NoSign } else { Plus };
188 }
189 }
190 self
191 }
192}
193
194impl Not for &BigInt {
195 type Output = BigInt;
196
197 fn not(self) -> BigInt {
198 match self.sign {
199 NoSign => -BigInt::one(),
200 Plus => -BigInt::from(&self.data + 1u32),
201 Minus => BigInt::from(&self.data - 1u32),
202 }
203 }
204}
205
206impl Zero for BigInt {
207 #[inline]
208 fn zero() -> BigInt {
209 Self::ZERO
210 }
211
212 #[inline]
213 fn set_zero(&mut self) {
214 self.data.set_zero();
215 self.sign = NoSign;
216 }
217
218 #[inline]
219 fn is_zero(&self) -> bool {
220 self.sign == NoSign
221 }
222}
223
224impl ConstZero for BigInt {
225 const ZERO: Self = Self::ZERO;
227}
228
229impl One for BigInt {
230 #[inline]
231 fn one() -> BigInt {
232 BigInt {
233 sign: Plus,
234 data: BigUint::one(),
235 }
236 }
237
238 #[inline]
239 fn set_one(&mut self) {
240 self.data.set_one();
241 self.sign = Plus;
242 }
243
244 #[inline]
245 fn is_one(&self) -> bool {
246 self.sign == Plus && self.data.is_one()
247 }
248}
249
250impl Signed for BigInt {
251 #[inline]
252 fn abs(&self) -> BigInt {
253 match self.sign {
254 Plus | NoSign => self.clone(),
255 Minus => BigInt::from(self.data.clone()),
256 }
257 }
258
259 #[inline]
260 fn abs_sub(&self, other: &BigInt) -> BigInt {
261 if *self <= *other {
262 Self::ZERO
263 } else {
264 self - other
265 }
266 }
267
268 #[inline]
269 fn signum(&self) -> BigInt {
270 match self.sign {
271 Plus => BigInt::one(),
272 Minus => -BigInt::one(),
273 NoSign => Self::ZERO,
274 }
275 }
276
277 #[inline]
278 fn is_positive(&self) -> bool {
279 self.sign == Plus
280 }
281
282 #[inline]
283 fn is_negative(&self) -> bool {
284 self.sign == Minus
285 }
286}
287
288trait UnsignedAbs {
289 type Unsigned;
290
291 fn checked_uabs(self) -> CheckedUnsignedAbs<Self::Unsigned>;
292}
293
294enum CheckedUnsignedAbs<T> {
295 Positive(T),
296 Negative(T),
297}
298use self::CheckedUnsignedAbs::{Negative, Positive};
299
300macro_rules! impl_unsigned_abs {
301 ($Signed:ty, $Unsigned:ty) => {
302 impl UnsignedAbs for $Signed {
303 type Unsigned = $Unsigned;
304
305 #[inline]
306 fn checked_uabs(self) -> CheckedUnsignedAbs<Self::Unsigned> {
307 if self >= 0 {
308 Positive(self as $Unsigned)
309 } else {
310 Negative(self.wrapping_neg() as $Unsigned)
311 }
312 }
313 }
314 };
315}
316impl UnsignedAbs for i8 {
type Unsigned = u8;
#[inline]
fn checked_uabs(self) -> CheckedUnsignedAbs<Self::Unsigned> {
if self >= 0 {
Positive(self as u8)
} else { Negative(self.wrapping_neg() as u8) }
}
}impl_unsigned_abs!(i8, u8);
317impl UnsignedAbs for i16 {
type Unsigned = u16;
#[inline]
fn checked_uabs(self) -> CheckedUnsignedAbs<Self::Unsigned> {
if self >= 0 {
Positive(self as u16)
} else { Negative(self.wrapping_neg() as u16) }
}
}impl_unsigned_abs!(i16, u16);
318impl UnsignedAbs for i32 {
type Unsigned = u32;
#[inline]
fn checked_uabs(self) -> CheckedUnsignedAbs<Self::Unsigned> {
if self >= 0 {
Positive(self as u32)
} else { Negative(self.wrapping_neg() as u32) }
}
}impl_unsigned_abs!(i32, u32);
319impl UnsignedAbs for i64 {
type Unsigned = u64;
#[inline]
fn checked_uabs(self) -> CheckedUnsignedAbs<Self::Unsigned> {
if self >= 0 {
Positive(self as u64)
} else { Negative(self.wrapping_neg() as u64) }
}
}impl_unsigned_abs!(i64, u64);
320impl UnsignedAbs for i128 {
type Unsigned = u128;
#[inline]
fn checked_uabs(self) -> CheckedUnsignedAbs<Self::Unsigned> {
if self >= 0 {
Positive(self as u128)
} else { Negative(self.wrapping_neg() as u128) }
}
}impl_unsigned_abs!(i128, u128);
321impl UnsignedAbs for isize {
type Unsigned = usize;
#[inline]
fn checked_uabs(self) -> CheckedUnsignedAbs<Self::Unsigned> {
if self >= 0 {
Positive(self as usize)
} else { Negative(self.wrapping_neg() as usize) }
}
}impl_unsigned_abs!(isize, usize);
322
323impl Neg for BigInt {
324 type Output = BigInt;
325
326 #[inline]
327 fn neg(mut self) -> BigInt {
328 self.sign = -self.sign;
329 self
330 }
331}
332
333impl Neg for &BigInt {
334 type Output = BigInt;
335
336 #[inline]
337 fn neg(self) -> BigInt {
338 -self.clone()
339 }
340}
341
342impl Integer for BigInt {
343 #[inline]
344 fn div_rem(&self, other: &BigInt) -> (BigInt, BigInt) {
345 let (d_ui, r_ui) = self.data.div_rem(&other.data);
347 let d = BigInt::from_biguint(self.sign, d_ui);
348 let r = BigInt::from_biguint(self.sign, r_ui);
349 if other.is_negative() {
350 (-d, r)
351 } else {
352 (d, r)
353 }
354 }
355
356 #[inline]
357 fn div_floor(&self, other: &BigInt) -> BigInt {
358 let (d_ui, m) = self.data.div_mod_floor(&other.data);
359 let d = BigInt::from(d_ui);
360 match (self.sign, other.sign) {
361 (Plus, Plus) | (NoSign, Plus) | (Minus, Minus) => d,
362 (Plus, Minus) | (NoSign, Minus) | (Minus, Plus) => {
363 if m.is_zero() {
364 -d
365 } else {
366 -d - 1u32
367 }
368 }
369 (_, NoSign) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
370 }
371 }
372
373 #[inline]
374 fn mod_floor(&self, other: &BigInt) -> BigInt {
375 let m_ui = self.data.mod_floor(&other.data);
377 let m = BigInt::from_biguint(other.sign, m_ui);
378 match (self.sign, other.sign) {
379 (Plus, Plus) | (NoSign, Plus) | (Minus, Minus) => m,
380 (Plus, Minus) | (NoSign, Minus) | (Minus, Plus) => {
381 if m.is_zero() {
382 m
383 } else {
384 other - m
385 }
386 }
387 (_, NoSign) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
388 }
389 }
390
391 fn div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt) {
392 let (d_ui, m_ui) = self.data.div_mod_floor(&other.data);
394 let d = BigInt::from(d_ui);
395 let m = BigInt::from_biguint(other.sign, m_ui);
396 match (self.sign, other.sign) {
397 (Plus, Plus) | (NoSign, Plus) | (Minus, Minus) => (d, m),
398 (Plus, Minus) | (NoSign, Minus) | (Minus, Plus) => {
399 if m.is_zero() {
400 (-d, m)
401 } else {
402 (-d - 1u32, other - m)
403 }
404 }
405 (_, NoSign) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
406 }
407 }
408
409 #[inline]
410 fn div_ceil(&self, other: &Self) -> Self {
411 let (d_ui, m) = self.data.div_mod_floor(&other.data);
412 let d = BigInt::from(d_ui);
413 match (self.sign, other.sign) {
414 (Plus, Minus) | (NoSign, Minus) | (Minus, Plus) => -d,
415 (Plus, Plus) | (NoSign, Plus) | (Minus, Minus) => {
416 if m.is_zero() {
417 d
418 } else {
419 d + 1u32
420 }
421 }
422 (_, NoSign) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
423 }
424 }
425
426 #[inline]
430 fn gcd(&self, other: &BigInt) -> BigInt {
431 BigInt::from(self.data.gcd(&other.data))
432 }
433
434 #[inline]
436 fn lcm(&self, other: &BigInt) -> BigInt {
437 BigInt::from(self.data.lcm(&other.data))
438 }
439
440 #[inline]
443 fn gcd_lcm(&self, other: &BigInt) -> (BigInt, BigInt) {
444 let (gcd, lcm) = self.data.gcd_lcm(&other.data);
445 (BigInt::from(gcd), BigInt::from(lcm))
446 }
447
448 #[inline]
450 fn extended_gcd_lcm(&self, other: &BigInt) -> (num_integer::ExtendedGcd<BigInt>, BigInt) {
451 let egcd = self.extended_gcd(other);
452 let lcm = if egcd.gcd.is_zero() {
453 Self::ZERO
454 } else {
455 BigInt::from(&self.data / &egcd.gcd.data * &other.data)
456 };
457 (egcd, lcm)
458 }
459
460 #[inline]
462 fn divides(&self, other: &BigInt) -> bool {
463 self.is_multiple_of(other)
464 }
465
466 #[inline]
468 fn is_multiple_of(&self, other: &BigInt) -> bool {
469 self.data.is_multiple_of(&other.data)
470 }
471
472 #[inline]
474 fn is_even(&self) -> bool {
475 self.data.is_even()
476 }
477
478 #[inline]
480 fn is_odd(&self) -> bool {
481 self.data.is_odd()
482 }
483
484 #[inline]
486 fn next_multiple_of(&self, other: &Self) -> Self {
487 let m = self.mod_floor(other);
488 if m.is_zero() {
489 self.clone()
490 } else {
491 self + (other - m)
492 }
493 }
494 #[inline]
496 fn prev_multiple_of(&self, other: &Self) -> Self {
497 self - self.mod_floor(other)
498 }
499
500 fn dec(&mut self) {
501 *self -= 1u32;
502 }
503
504 fn inc(&mut self) {
505 *self += 1u32;
506 }
507}
508
509impl Roots for BigInt {
510 fn nth_root(&self, n: u32) -> Self {
511 if !!(self.is_negative() && n.is_even()) {
{
::core::panicking::panic_fmt(format_args!("root of degree {0} is imaginary",
n));
}
};assert!(
512 !(self.is_negative() && n.is_even()),
513 "root of degree {} is imaginary",
514 n
515 );
516
517 BigInt::from_biguint(self.sign, self.data.nth_root(n))
518 }
519
520 fn sqrt(&self) -> Self {
521 if !!self.is_negative() {
{
::core::panicking::panic_fmt(format_args!("square root is imaginary"));
}
};assert!(!self.is_negative(), "square root is imaginary");
522
523 BigInt::from_biguint(self.sign, self.data.sqrt())
524 }
525
526 fn cbrt(&self) -> Self {
527 BigInt::from_biguint(self.sign, self.data.cbrt())
528 }
529}
530
531impl IntDigits for BigInt {
532 #[inline]
533 fn digits(&self) -> &[BigDigit] {
534 self.data.digits()
535 }
536 #[inline]
537 fn digits_mut(&mut self) -> &mut Vec<BigDigit> {
538 self.data.digits_mut()
539 }
540 #[inline]
541 fn normalize(&mut self) {
542 self.data.normalize();
543 if self.data.is_zero() {
544 self.sign = NoSign;
545 }
546 }
547 #[inline]
548 fn capacity(&self) -> usize {
549 self.data.capacity()
550 }
551 #[inline]
552 fn len(&self) -> usize {
553 self.data.len()
554 }
555}
556
557pub trait ToBigInt {
561 fn to_bigint(&self) -> Option<BigInt>;
563}
564
565impl BigInt {
566 pub const ZERO: Self = BigInt {
568 sign: NoSign,
569 data: BigUint::ZERO,
570 };
571
572 #[inline]
576 pub fn new(sign: Sign, digits: Vec<u32>) -> BigInt {
577 BigInt::from_biguint(sign, BigUint::new(digits))
578 }
579
580 #[inline]
584 pub fn from_biguint(mut sign: Sign, mut data: BigUint) -> BigInt {
585 if sign == NoSign {
586 data.assign_from_slice(&[]);
587 } else if data.is_zero() {
588 sign = NoSign;
589 }
590
591 BigInt { sign, data }
592 }
593
594 #[inline]
598 pub fn from_slice(sign: Sign, slice: &[u32]) -> BigInt {
599 BigInt::from_biguint(sign, BigUint::from_slice(slice))
600 }
601
602 #[inline]
606 pub fn assign_from_slice(&mut self, sign: Sign, slice: &[u32]) {
607 if sign == NoSign {
608 self.set_zero();
609 } else {
610 self.data.assign_from_slice(slice);
611 self.sign = if self.data.is_zero() { NoSign } else { sign };
612 }
613 }
614
615 #[inline]
634 pub fn from_bytes_be(sign: Sign, bytes: &[u8]) -> BigInt {
635 BigInt::from_biguint(sign, BigUint::from_bytes_be(bytes))
636 }
637
638 #[inline]
642 pub fn from_bytes_le(sign: Sign, bytes: &[u8]) -> BigInt {
643 BigInt::from_biguint(sign, BigUint::from_bytes_le(bytes))
644 }
645
646 #[inline]
651 pub fn from_signed_bytes_be(digits: &[u8]) -> BigInt {
652 convert::from_signed_bytes_be(digits)
653 }
654
655 #[inline]
659 pub fn from_signed_bytes_le(digits: &[u8]) -> BigInt {
660 convert::from_signed_bytes_le(digits)
661 }
662
663 #[inline]
675 pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigInt> {
676 let s = str::from_utf8(buf).ok()?;
677 BigInt::from_str_radix(s, radix).ok()
678 }
679
680 pub fn from_radix_be(sign: Sign, buf: &[u8], radix: u32) -> Option<BigInt> {
697 let u = BigUint::from_radix_be(buf, radix)?;
698 Some(BigInt::from_biguint(sign, u))
699 }
700
701 pub fn from_radix_le(sign: Sign, buf: &[u8], radix: u32) -> Option<BigInt> {
718 let u = BigUint::from_radix_le(buf, radix)?;
719 Some(BigInt::from_biguint(sign, u))
720 }
721
722 #[inline]
733 pub fn to_bytes_be(&self) -> (Sign, Vec<u8>) {
734 (self.sign, self.data.to_bytes_be())
735 }
736
737 #[inline]
748 pub fn to_bytes_le(&self) -> (Sign, Vec<u8>) {
749 (self.sign, self.data.to_bytes_le())
750 }
751
752 #[inline]
767 pub fn to_u32_digits(&self) -> (Sign, Vec<u32>) {
768 (self.sign, self.data.to_u32_digits())
769 }
770
771 #[inline]
787 pub fn to_u64_digits(&self) -> (Sign, Vec<u64>) {
788 (self.sign, self.data.to_u64_digits())
789 }
790
791 #[inline]
806 pub fn iter_u32_digits(&self) -> U32Digits<'_> {
807 self.data.iter_u32_digits()
808 }
809
810 #[inline]
826 pub fn iter_u64_digits(&self) -> U64Digits<'_> {
827 self.data.iter_u64_digits()
828 }
829
830 #[inline]
841 pub fn to_signed_bytes_be(&self) -> Vec<u8> {
842 convert::to_signed_bytes_be(self)
843 }
844
845 #[inline]
856 pub fn to_signed_bytes_le(&self) -> Vec<u8> {
857 convert::to_signed_bytes_le(self)
858 }
859
860 #[inline]
872 pub fn to_str_radix(&self, radix: u32) -> String {
873 let mut v = to_str_radix_reversed(&self.data, radix);
874
875 if self.is_negative() {
876 v.push(b'-');
877 }
878
879 v.reverse();
880 unsafe { String::from_utf8_unchecked(v) }
881 }
882
883 #[inline]
898 pub fn to_radix_be(&self, radix: u32) -> (Sign, Vec<u8>) {
899 (self.sign, self.data.to_radix_be(radix))
900 }
901
902 #[inline]
917 pub fn to_radix_le(&self, radix: u32) -> (Sign, Vec<u8>) {
918 (self.sign, self.data.to_radix_le(radix))
919 }
920
921 #[inline]
933 pub fn sign(&self) -> Sign {
934 self.sign
935 }
936
937 #[inline]
950 pub fn magnitude(&self) -> &BigUint {
951 &self.data
952 }
953
954 #[inline]
967 pub fn into_parts(self) -> (Sign, BigUint) {
968 (self.sign, self.data)
969 }
970
971 #[inline]
974 pub fn bits(&self) -> u64 {
975 self.data.bits()
976 }
977
978 #[inline]
980 pub fn to_biguint(&self) -> Option<BigUint> {
981 match self.sign {
982 Plus => Some(self.data.clone()),
983 NoSign => Some(BigUint::ZERO),
984 Minus => None,
985 }
986 }
987
988 #[inline]
989 pub fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
990 Some(self + v)
991 }
992
993 #[inline]
994 pub fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
995 Some(self - v)
996 }
997
998 #[inline]
999 pub fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
1000 Some(self * v)
1001 }
1002
1003 #[inline]
1004 pub fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
1005 if v.is_zero() {
1006 return None;
1007 }
1008 Some(self / v)
1009 }
1010
1011 pub fn pow(&self, exponent: u32) -> Self {
1013 Pow::pow(self, exponent)
1014 }
1015
1016 pub fn modpow(&self, exponent: &Self, modulus: &Self) -> Self {
1025 power::modpow(self, exponent, modulus)
1026 }
1027
1028 pub fn modinv(&self, modulus: &Self) -> Option<Self> {
1075 let result = self.data.modinv(&modulus.data)?;
1076 let (sign, mag) = match (self.is_negative(), modulus.is_negative()) {
1078 (false, false) => (Plus, result),
1079 (true, false) => (Plus, &modulus.data - result),
1080 (false, true) => (Minus, &modulus.data - result),
1081 (true, true) => (Minus, result),
1082 };
1083 Some(BigInt::from_biguint(sign, mag))
1084 }
1085
1086 pub fn sqrt(&self) -> Self {
1089 Roots::sqrt(self)
1090 }
1091
1092 pub fn cbrt(&self) -> Self {
1095 Roots::cbrt(self)
1096 }
1097
1098 pub fn nth_root(&self, n: u32) -> Self {
1101 Roots::nth_root(self, n)
1102 }
1103
1104 pub fn trailing_zeros(&self) -> Option<u64> {
1107 self.data.trailing_zeros()
1108 }
1109
1110 pub fn bit(&self, bit: u64) -> bool {
1113 if self.is_negative() {
1114 if bit >= u64::from(crate::big_digit::BITS) * self.len() as u64 {
1120 true
1121 } else {
1122 let trailing_zeros = self.data.trailing_zeros().unwrap();
1123 match Ord::cmp(&bit, &trailing_zeros) {
1124 Ordering::Less => false,
1125 Ordering::Equal => true,
1126 Ordering::Greater => !self.data.bit(bit),
1127 }
1128 }
1129 } else {
1130 self.data.bit(bit)
1131 }
1132 }
1133
1134 pub fn set_bit(&mut self, bit: u64, value: bool) {
1141 match self.sign {
1142 Sign::Plus => self.data.set_bit(bit, value),
1143 Sign::Minus => bits::set_negative_bit(self, bit, value),
1144 Sign::NoSign => {
1145 if value {
1146 self.data.set_bit(bit, true);
1147 self.sign = Sign::Plus;
1148 } else {
1149 }
1151 }
1152 }
1153 self.normalize();
1155 }
1156}
1157
1158impl num_traits::FromBytes for BigInt {
1159 type Bytes = [u8];
1160
1161 fn from_be_bytes(bytes: &Self::Bytes) -> Self {
1162 Self::from_signed_bytes_be(bytes)
1163 }
1164
1165 fn from_le_bytes(bytes: &Self::Bytes) -> Self {
1166 Self::from_signed_bytes_le(bytes)
1167 }
1168}
1169
1170impl num_traits::ToBytes for BigInt {
1171 type Bytes = Vec<u8>;
1172
1173 fn to_be_bytes(&self) -> Self::Bytes {
1174 self.to_signed_bytes_be()
1175 }
1176
1177 fn to_le_bytes(&self) -> Self::Bytes {
1178 self.to_signed_bytes_le()
1179 }
1180}
1181
1182#[test]
1183fn test_from_biguint() {
1184 fn check(inp_s: Sign, inp_n: usize, ans_s: Sign, ans_n: usize) {
1185 let inp = BigInt::from_biguint(inp_s, BigUint::from(inp_n));
1186 let ans = BigInt {
1187 sign: ans_s,
1188 data: BigUint::from(ans_n),
1189 };
1190 assert_eq!(inp, ans);
1191 }
1192 check(Plus, 1, Plus, 1);
1193 check(Plus, 0, NoSign, 0);
1194 check(Minus, 1, Minus, 1);
1195 check(NoSign, 1, NoSign, 0);
1196}
1197
1198#[test]
1199fn test_from_slice() {
1200 fn check(inp_s: Sign, inp_n: u32, ans_s: Sign, ans_n: u32) {
1201 let inp = BigInt::from_slice(inp_s, &[inp_n]);
1202 let ans = BigInt {
1203 sign: ans_s,
1204 data: BigUint::from(ans_n),
1205 };
1206 assert_eq!(inp, ans);
1207 }
1208 check(Plus, 1, Plus, 1);
1209 check(Plus, 0, NoSign, 0);
1210 check(Minus, 1, Minus, 1);
1211 check(NoSign, 1, NoSign, 0);
1212}
1213
1214#[test]
1215fn test_assign_from_slice() {
1216 fn check(inp_s: Sign, inp_n: u32, ans_s: Sign, ans_n: u32) {
1217 let mut inp = BigInt::from_slice(Minus, &[2627_u32, 0_u32, 9182_u32, 42_u32]);
1218 inp.assign_from_slice(inp_s, &[inp_n]);
1219 let ans = BigInt {
1220 sign: ans_s,
1221 data: BigUint::from(ans_n),
1222 };
1223 assert_eq!(inp, ans);
1224 }
1225 check(Plus, 1, Plus, 1);
1226 check(Plus, 0, NoSign, 0);
1227 check(Minus, 1, Minus, 1);
1228 check(NoSign, 1, NoSign, 0);
1229}