1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A Big integer (signed version: `BigInt`, unsigned version: `BigUint`).
13 //! A `BigUint` is represented as an array of `BigDigit`s.
14 //! A `BigInt` is a combination of `BigUint` and `Sign`.
16 //! Common numerical operations are overloaded, so we can treat them
17 //! the same way we treat other numbers.
22 //! use num::bigint::BigUint;
23 //! use std::num::{Zero, One};
24 //! use std::mem::replace;
26 //! // Calculate large fibonacci numbers.
27 //! fn fib(n: uint) -> BigUint {
28 //! let mut f0: BigUint = Zero::zero();
29 //! let mut f1: BigUint = One::one();
30 //! for _ in range(0, n) {
32 //! // This is a low cost way of swapping f0 with f1 and f1 with f2.
33 //! f0 = replace(&mut f1, f2);
38 //! // This is a very large number.
39 //! println!("fib(1000) = {}", fib(1000));
42 //! It's easy to generate large random numbers:
45 //! use num::bigint::{ToBigInt, RandBigInt};
48 //! let mut rng = rand::task_rng();
49 //! let a = rng.gen_bigint(1000u);
51 //! let low = -10000i.to_bigint().unwrap();
52 //! let high = 10000i.to_bigint().unwrap();
53 //! let b = rng.gen_bigint_range(&low, &high);
55 //! // Probably an even larger number.
56 //! println!("{}", a * b);
62 use std::{cmp, fmt, hash};
63 use std::default::Default;
64 use std::from_str::FromStr;
65 use std::num::CheckedDiv;
66 use std::num::{ToPrimitive, FromPrimitive};
67 use std::num::{Zero, One, ToStrRadix, FromStrRadix};
68 use std::string::String;
69 use std::{uint, i64, u64};
71 /// A `BigDigit` is a `BigUint`'s composing element.
72 pub type BigDigit = u32;
74 /// A `DoubleBigDigit` is the internal type used to do the computations. Its
75 /// size is the double of the size of `BigDigit`.
76 pub type DoubleBigDigit = u64;
78 pub static ZERO_BIG_DIGIT: BigDigit = 0;
79 static ZERO_VEC: [BigDigit, ..1] = [ZERO_BIG_DIGIT];
83 use super::DoubleBigDigit;
85 // `DoubleBigDigit` size dependent
86 pub static bits: uint = 32;
88 pub static base: DoubleBigDigit = 1 << bits;
89 static lo_mask: DoubleBigDigit = (-1 as DoubleBigDigit) >> bits;
92 fn get_hi(n: DoubleBigDigit) -> BigDigit { (n >> bits) as BigDigit }
94 fn get_lo(n: DoubleBigDigit) -> BigDigit { (n & lo_mask) as BigDigit }
96 /// Split one `DoubleBigDigit` into two `BigDigit`s.
98 pub fn from_doublebigdigit(n: DoubleBigDigit) -> (BigDigit, BigDigit) {
99 (get_hi(n), get_lo(n))
102 /// Join two `BigDigit`s into one `DoubleBigDigit`
104 pub fn to_doublebigdigit(hi: BigDigit, lo: BigDigit) -> DoubleBigDigit {
105 (lo as DoubleBigDigit) | ((hi as DoubleBigDigit) << bits)
109 /// A big unsigned integer type.
111 /// A `BigUint`-typed value `BigUint { data: vec!(a, b, c) }` represents a number
112 /// `(a + b * BigDigit::base + c * BigDigit::base^2)`.
118 impl PartialEq for BigUint {
120 fn eq(&self, other: &BigUint) -> bool {
121 match self.cmp(other) { Equal => true, _ => false }
124 impl Eq for BigUint {}
126 impl PartialOrd for BigUint {
128 fn partial_cmp(&self, other: &BigUint) -> Option<Ordering> {
129 Some(self.cmp(other))
133 impl Ord for BigUint {
135 fn cmp(&self, other: &BigUint) -> Ordering {
136 let (s_len, o_len) = (self.data.len(), other.data.len());
137 if s_len < o_len { return Less; }
138 if s_len > o_len { return Greater; }
140 for (&self_i, &other_i) in self.data.iter().rev().zip(other.data.iter().rev()) {
141 if self_i < other_i { return Less; }
142 if self_i > other_i { return Greater; }
148 impl Default for BigUint {
150 fn default() -> BigUint { Zero::zero() }
153 impl<S: hash::Writer> hash::Hash<S> for BigUint {
154 fn hash(&self, state: &mut S) {
155 // hash 0 in case it's all 0's
158 let mut found_first_value = false;
159 for elem in self.data.iter().rev() {
160 // don't hash any leading 0's, they shouldn't affect the hash
161 if found_first_value || *elem != 0 {
162 found_first_value = true;
169 impl fmt::Show for BigUint {
170 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
171 write!(f, "{}", self.to_str_radix(10))
175 impl FromStr for BigUint {
177 fn from_str(s: &str) -> Option<BigUint> {
178 FromStrRadix::from_str_radix(s, 10)
182 impl Num for BigUint {}
184 impl BitAnd<BigUint, BigUint> for BigUint {
185 fn bitand(&self, other: &BigUint) -> BigUint {
186 BigUint::new(self.data.iter().zip(other.data.iter()).map(|(ai, bi)| *ai & *bi).collect())
190 impl BitOr<BigUint, BigUint> for BigUint {
191 fn bitor(&self, other: &BigUint) -> BigUint {
192 let zeros = ZERO_VEC.iter().cycle();
193 let (a, b) = if self.data.len() > other.data.len() { (self, other) } else { (other, self) };
194 let ored = a.data.iter().zip(b.data.iter().chain(zeros)).map(
197 return BigUint::new(ored);
201 impl BitXor<BigUint, BigUint> for BigUint {
202 fn bitxor(&self, other: &BigUint) -> BigUint {
203 let zeros = ZERO_VEC.iter().cycle();
204 let (a, b) = if self.data.len() > other.data.len() { (self, other) } else { (other, self) };
205 let xored = a.data.iter().zip(b.data.iter().chain(zeros)).map(
208 return BigUint::new(xored);
212 impl Shl<uint, BigUint> for BigUint {
214 fn shl(&self, rhs: &uint) -> BigUint {
215 let n_unit = *rhs / BigDigit::bits;
216 let n_bits = *rhs % BigDigit::bits;
217 return self.shl_unit(n_unit).shl_bits(n_bits);
221 impl Shr<uint, BigUint> for BigUint {
223 fn shr(&self, rhs: &uint) -> BigUint {
224 let n_unit = *rhs / BigDigit::bits;
225 let n_bits = *rhs % BigDigit::bits;
226 return self.shr_unit(n_unit).shr_bits(n_bits);
230 impl Zero for BigUint {
232 fn zero() -> BigUint { BigUint::new(Vec::new()) }
235 fn is_zero(&self) -> bool { self.data.is_empty() }
238 impl One for BigUint {
240 fn one() -> BigUint { BigUint::new(vec!(1)) }
243 impl Unsigned for BigUint {}
245 impl Add<BigUint, BigUint> for BigUint {
246 fn add(&self, other: &BigUint) -> BigUint {
247 let zeros = ZERO_VEC.iter().cycle();
248 let (a, b) = if self.data.len() > other.data.len() { (self, other) } else { (other, self) };
251 let mut sum: Vec<BigDigit> = a.data.iter().zip(b.data.iter().chain(zeros)).map(|(ai, bi)| {
252 let (hi, lo) = BigDigit::from_doublebigdigit(
253 (*ai as DoubleBigDigit) + (*bi as DoubleBigDigit) + (carry as DoubleBigDigit));
257 if carry != 0 { sum.push(carry); }
258 return BigUint::new(sum);
262 impl Sub<BigUint, BigUint> for BigUint {
263 fn sub(&self, other: &BigUint) -> BigUint {
264 let new_len = cmp::max(self.data.len(), other.data.len());
265 let zeros = ZERO_VEC.iter().cycle();
266 let (a, b) = (self.data.iter().chain(zeros.clone()), other.data.iter().chain(zeros));
269 let diff: Vec<BigDigit> = a.take(new_len).zip(b).map(|(ai, bi)| {
270 let (hi, lo) = BigDigit::from_doublebigdigit(
272 + (*ai as DoubleBigDigit)
273 - (*bi as DoubleBigDigit)
274 - (borrow as DoubleBigDigit)
277 hi * (base) + lo == 1*(base) + ai - bi - borrow
278 => ai - bi - borrow < 0 <=> hi == 0
280 borrow = if hi == 0 { 1 } else { 0 };
285 "Cannot subtract other from self because other is larger than self.");
286 return BigUint::new(diff);
290 impl Mul<BigUint, BigUint> for BigUint {
291 fn mul(&self, other: &BigUint) -> BigUint {
292 if self.is_zero() || other.is_zero() { return Zero::zero(); }
294 let (s_len, o_len) = (self.data.len(), other.data.len());
295 if s_len == 1 { return mul_digit(other, self.data.as_slice()[0]); }
296 if o_len == 1 { return mul_digit(self, other.data.as_slice()[0]); }
298 // Using Karatsuba multiplication
299 // (a1 * base + a0) * (b1 * base + b0)
300 // = a1*b1 * base^2 +
301 // (a1*b1 + a0*b0 - (a1-b0)*(b1-a0)) * base +
303 let half_len = cmp::max(s_len, o_len) / 2;
304 let (s_hi, s_lo) = cut_at(self, half_len);
305 let (o_hi, o_lo) = cut_at(other, half_len);
307 let ll = s_lo * o_lo;
308 let hh = s_hi * o_hi;
310 let (s1, n1) = sub_sign(s_hi, s_lo);
311 let (s2, n2) = sub_sign(o_hi, o_lo);
313 (Equal, _) | (_, Equal) => hh + ll,
314 (Less, Greater) | (Greater, Less) => hh + ll + (n1 * n2),
315 (Less, Less) | (Greater, Greater) => hh + ll - (n1 * n2)
319 return ll + mm.shl_unit(half_len) + hh.shl_unit(half_len * 2);
322 fn mul_digit(a: &BigUint, n: BigDigit) -> BigUint {
323 if n == 0 { return Zero::zero(); }
324 if n == 1 { return (*a).clone(); }
327 let mut prod: Vec<BigDigit> = a.data.iter().map(|ai| {
328 let (hi, lo) = BigDigit::from_doublebigdigit(
329 (*ai as DoubleBigDigit) * (n as DoubleBigDigit) + (carry as DoubleBigDigit)
334 if carry != 0 { prod.push(carry); }
335 return BigUint::new(prod);
339 fn cut_at(a: &BigUint, n: uint) -> (BigUint, BigUint) {
340 let mid = cmp::min(a.data.len(), n);
341 return (BigUint::from_slice(a.data.slice(mid, a.data.len())),
342 BigUint::from_slice(a.data.slice(0, mid)));
346 fn sub_sign(a: BigUint, b: BigUint) -> (Ordering, BigUint) {
348 Less => (Less, b - a),
349 Greater => (Greater, a - b),
350 _ => (Equal, Zero::zero())
356 impl Div<BigUint, BigUint> for BigUint {
358 fn div(&self, other: &BigUint) -> BigUint {
359 let (q, _) = self.div_rem(other);
364 impl Rem<BigUint, BigUint> for BigUint {
366 fn rem(&self, other: &BigUint) -> BigUint {
367 let (_, r) = self.div_rem(other);
372 impl Neg<BigUint> for BigUint {
374 fn neg(&self) -> BigUint { fail!() }
377 impl CheckedAdd for BigUint {
379 fn checked_add(&self, v: &BigUint) -> Option<BigUint> {
380 return Some(self.add(v));
384 impl CheckedSub for BigUint {
386 fn checked_sub(&self, v: &BigUint) -> Option<BigUint> {
390 return Some(self.sub(v));
394 impl CheckedMul for BigUint {
396 fn checked_mul(&self, v: &BigUint) -> Option<BigUint> {
397 return Some(self.mul(v));
401 impl CheckedDiv for BigUint {
403 fn checked_div(&self, v: &BigUint) -> Option<BigUint> {
407 return Some(self.div(v));
411 impl Integer for BigUint {
413 fn div_rem(&self, other: &BigUint) -> (BigUint, BigUint) {
414 self.div_mod_floor(other)
418 fn div_floor(&self, other: &BigUint) -> BigUint {
419 let (d, _) = self.div_mod_floor(other);
424 fn mod_floor(&self, other: &BigUint) -> BigUint {
425 let (_, m) = self.div_mod_floor(other);
429 fn div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint) {
430 if other.is_zero() { fail!() }
431 if self.is_zero() { return (Zero::zero(), Zero::zero()); }
432 if *other == One::one() { return ((*self).clone(), Zero::zero()); }
434 match self.cmp(other) {
435 Less => return (Zero::zero(), (*self).clone()),
436 Equal => return (One::one(), Zero::zero()),
437 Greater => {} // Do nothing
441 let mut n = *other.data.last().unwrap();
442 while n < (1 << BigDigit::bits - 2) {
446 assert!(shift < BigDigit::bits);
447 let (d, m) = div_mod_floor_inner(self << shift, other << shift);
448 return (d, m >> shift);
451 fn div_mod_floor_inner(a: BigUint, b: BigUint) -> (BigUint, BigUint) {
453 let mut d: BigUint = Zero::zero();
456 let (d0, d_unit, b_unit) = div_estimate(&m, &b, n);
458 let mut prod = b * d0;
460 // FIXME(#5992): assignment operator overloads
463 // FIXME(#5992): assignment operator overloads
472 // FIXME(#5992): assignment operator overloads
475 // FIXME(#5992): assignment operator overloads
483 fn div_estimate(a: &BigUint, b: &BigUint, n: uint)
484 -> (BigUint, BigUint, BigUint) {
485 if a.data.len() < n {
486 return (Zero::zero(), Zero::zero(), (*a).clone());
489 let an = a.data.tailn(a.data.len() - n);
490 let bn = *b.data.last().unwrap();
491 let mut d = Vec::with_capacity(an.len());
493 for elt in an.iter().rev() {
494 let ai = BigDigit::to_doublebigdigit(carry, *elt);
495 let di = ai / (bn as DoubleBigDigit);
496 assert!(di < BigDigit::base);
497 carry = (ai % (bn as DoubleBigDigit)) as BigDigit;
498 d.push(di as BigDigit)
502 let shift = (a.data.len() - an.len()) - (b.data.len() - 1);
504 return (BigUint::new(d), One::one(), (*b).clone());
506 let one: BigUint = One::one();
507 return (BigUint::new(d).shl_unit(shift),
513 /// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
515 /// The result is always positive.
517 fn gcd(&self, other: &BigUint) -> BigUint {
518 // Use Euclid's algorithm
519 let mut m = (*self).clone();
520 let mut n = (*other).clone();
529 /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
531 fn lcm(&self, other: &BigUint) -> BigUint { ((*self * *other) / self.gcd(other)) }
533 /// Deprecated, use `is_multiple_of` instead.
534 #[deprecated = "function renamed to `is_multiple_of`"]
536 fn divides(&self, other: &BigUint) -> bool { return self.is_multiple_of(other); }
538 /// Returns `true` if the number is a multiple of `other`.
540 fn is_multiple_of(&self, other: &BigUint) -> bool { (*self % *other).is_zero() }
542 /// Returns `true` if the number is divisible by `2`.
544 fn is_even(&self) -> bool {
545 // Considering only the last digit.
546 match self.data.as_slice().head() {
547 Some(x) => x.is_even(),
552 /// Returns `true` if the number is not divisible by `2`.
554 fn is_odd(&self) -> bool { !self.is_even() }
557 impl ToPrimitive for BigUint {
559 fn to_i64(&self) -> Option<i64> {
560 self.to_u64().and_then(|n| {
561 // If top bit of u64 is set, it's too large to convert to i64.
570 // `DoubleBigDigit` size dependent
572 fn to_u64(&self) -> Option<u64> {
573 match self.data.len() {
575 1 => Some(self.data.as_slice()[0] as u64),
576 2 => Some(BigDigit::to_doublebigdigit(self.data.as_slice()[1], self.data.as_slice()[0])
583 impl FromPrimitive for BigUint {
585 fn from_i64(n: i64) -> Option<BigUint> {
587 FromPrimitive::from_u64(n as u64)
595 // `DoubleBigDigit` size dependent
597 fn from_u64(n: u64) -> Option<BigUint> {
598 let n = match BigDigit::from_doublebigdigit(n) {
599 (0, 0) => Zero::zero(),
600 (0, n0) => BigUint::new(vec!(n0)),
601 (n1, n0) => BigUint::new(vec!(n0, n1))
607 /// A generic trait for converting a value to a `BigUint`.
608 pub trait ToBigUint {
609 /// Converts the value of `self` to a `BigUint`.
610 fn to_biguint(&self) -> Option<BigUint>;
613 impl ToBigUint for BigInt {
615 fn to_biguint(&self) -> Option<BigUint> {
616 if self.sign == Plus {
617 Some(self.data.clone())
618 } else if self.sign == Zero {
626 impl ToBigUint for BigUint {
628 fn to_biguint(&self) -> Option<BigUint> {
633 macro_rules! impl_to_biguint(
634 ($T:ty, $from_ty:path) => {
635 impl ToBigUint for $T {
637 fn to_biguint(&self) -> Option<BigUint> {
644 impl_to_biguint!(int, FromPrimitive::from_int)
645 impl_to_biguint!(i8, FromPrimitive::from_i8)
646 impl_to_biguint!(i16, FromPrimitive::from_i16)
647 impl_to_biguint!(i32, FromPrimitive::from_i32)
648 impl_to_biguint!(i64, FromPrimitive::from_i64)
649 impl_to_biguint!(uint, FromPrimitive::from_uint)
650 impl_to_biguint!(u8, FromPrimitive::from_u8)
651 impl_to_biguint!(u16, FromPrimitive::from_u16)
652 impl_to_biguint!(u32, FromPrimitive::from_u32)
653 impl_to_biguint!(u64, FromPrimitive::from_u64)
655 impl ToStrRadix for BigUint {
656 fn to_str_radix(&self, radix: uint) -> String {
657 assert!(1 < radix && radix <= 16, "The radix must be within (1, 16]");
658 let (base, max_len) = get_radix_base(radix);
659 if base == BigDigit::base {
660 return fill_concat(self.data.as_slice(), radix, max_len)
662 return fill_concat(convert_base(self, base).as_slice(), radix, max_len);
664 fn convert_base(n: &BigUint, base: DoubleBigDigit) -> Vec<BigDigit> {
665 let divider = base.to_biguint().unwrap();
666 let mut result = Vec::new();
667 let mut m = n.clone();
669 let (d, m0) = m.div_mod_floor(÷r);
670 result.push(m0.to_uint().unwrap() as BigDigit);
674 result.push(m.to_uint().unwrap() as BigDigit);
679 fn fill_concat(v: &[BigDigit], radix: uint, l: uint) -> String {
681 return "0".to_string()
683 let mut s = String::with_capacity(v.len() * l);
684 for n in v.iter().rev() {
685 let ss = (*n as uint).to_str_radix(radix);
686 s.push_str("0".repeat(l - ss.len()).as_slice());
687 s.push_str(ss.as_slice());
689 s.as_slice().trim_left_chars('0').to_string()
694 impl FromStrRadix for BigUint {
695 /// Creates and initializes a `BigUint`.
697 fn from_str_radix(s: &str, radix: uint) -> Option<BigUint> {
698 BigUint::parse_bytes(s.as_bytes(), radix)
703 /// Creates and initializes a `BigUint`.
705 /// The digits are be in base 2^32.
707 pub fn new(mut digits: Vec<BigDigit>) -> BigUint {
708 // omit trailing zeros
709 let new_len = digits.iter().rposition(|n| *n != 0).map_or(0, |p| p + 1);
710 digits.truncate(new_len);
711 BigUint { data: digits }
714 /// Creates and initializes a `BigUint`.
716 /// The digits are be in base 2^32.
718 pub fn from_slice(slice: &[BigDigit]) -> BigUint {
719 BigUint::new(Vec::from_slice(slice))
722 /// Creates and initializes a `BigUint`.
723 pub fn parse_bytes(buf: &[u8], radix: uint) -> Option<BigUint> {
724 let (base, unit_len) = get_radix_base(radix);
725 let base_num = match base.to_biguint() {
726 Some(base_num) => base_num,
727 None => { return None; }
730 let mut end = buf.len();
731 let mut n: BigUint = Zero::zero();
732 let mut power: BigUint = One::one();
734 let start = cmp::max(end, unit_len) - unit_len;
735 match uint::parse_bytes(buf.slice(start, end), radix) {
737 let d: Option<BigUint> = FromPrimitive::from_uint(d);
740 // FIXME(#5992): assignment operator overloads
744 None => { return None; }
747 None => { return None; }
753 // FIXME(#5992): assignment operator overloads
754 // power *= base_num;
755 power = power * base_num;
760 fn shl_unit(&self, n_unit: uint) -> BigUint {
761 if n_unit == 0 || self.is_zero() { return (*self).clone(); }
763 BigUint::new(Vec::from_elem(n_unit, ZERO_BIG_DIGIT).append(self.data.as_slice()))
767 fn shl_bits(&self, n_bits: uint) -> BigUint {
768 if n_bits == 0 || self.is_zero() { return (*self).clone(); }
771 let mut shifted: Vec<BigDigit> = self.data.iter().map(|elem| {
772 let (hi, lo) = BigDigit::from_doublebigdigit(
773 (*elem as DoubleBigDigit) << n_bits | (carry as DoubleBigDigit)
778 if carry != 0 { shifted.push(carry); }
779 return BigUint::new(shifted);
783 fn shr_unit(&self, n_unit: uint) -> BigUint {
784 if n_unit == 0 { return (*self).clone(); }
785 if self.data.len() < n_unit { return Zero::zero(); }
786 return BigUint::from_slice(
787 self.data.slice(n_unit, self.data.len())
792 fn shr_bits(&self, n_bits: uint) -> BigUint {
793 if n_bits == 0 || self.data.is_empty() { return (*self).clone(); }
796 let mut shifted_rev = Vec::with_capacity(self.data.len());
797 for elem in self.data.iter().rev() {
798 shifted_rev.push((*elem >> n_bits) | borrow);
799 borrow = *elem << (BigDigit::bits - n_bits);
801 let shifted = { shifted_rev.reverse(); shifted_rev };
802 return BigUint::new(shifted);
805 /// Determines the fewest bits necessary to express the `BigUint`.
806 pub fn bits(&self) -> uint {
807 if self.is_zero() { return 0; }
808 let zeros = self.data.last().unwrap().leading_zeros();
809 return self.data.len()*BigDigit::bits - (zeros as uint);
813 // `DoubleBigDigit` size dependent
815 fn get_radix_base(radix: uint) -> (DoubleBigDigit, uint) {
817 2 => (4294967296, 32),
818 3 => (3486784401, 20),
819 4 => (4294967296, 16),
820 5 => (1220703125, 13),
821 6 => (2176782336, 12),
822 7 => (1977326743, 11),
823 8 => (1073741824, 10),
824 9 => (3486784401, 10),
825 10 => (1000000000, 9),
826 11 => (2357947691, 9),
827 12 => (429981696, 8),
828 13 => (815730721, 8),
829 14 => (1475789056, 8),
830 15 => (2562890625, 8),
831 16 => (4294967296, 8),
832 _ => fail!("The radix must be within (1, 16]")
836 /// A Sign is a `BigInt`'s composing element.
837 #[deriving(PartialEq, PartialOrd, Eq, Ord, Clone, Show)]
838 pub enum Sign { Minus, Zero, Plus }
840 impl Neg<Sign> for Sign {
841 /// Negate Sign value.
843 fn neg(&self) -> Sign {
852 /// A big signed integer type.
859 impl PartialEq for BigInt {
861 fn eq(&self, other: &BigInt) -> bool {
862 self.cmp(other) == Equal
866 impl Eq for BigInt {}
868 impl PartialOrd for BigInt {
870 fn partial_cmp(&self, other: &BigInt) -> Option<Ordering> {
871 Some(self.cmp(other))
875 impl Ord for BigInt {
877 fn cmp(&self, other: &BigInt) -> Ordering {
878 let scmp = self.sign.cmp(&other.sign);
879 if scmp != Equal { return scmp; }
883 Plus => self.data.cmp(&other.data),
884 Minus => other.data.cmp(&self.data),
889 impl Default for BigInt {
891 fn default() -> BigInt { Zero::zero() }
894 impl fmt::Show for BigInt {
895 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
896 write!(f, "{}", self.to_str_radix(10))
900 impl<S: hash::Writer> hash::Hash<S> for BigInt {
901 fn hash(&self, state: &mut S) {
902 (self.sign == Plus).hash(state);
903 self.data.hash(state);
907 impl FromStr for BigInt {
909 fn from_str(s: &str) -> Option<BigInt> {
910 FromStrRadix::from_str_radix(s, 10)
914 impl Num for BigInt {}
916 impl Shl<uint, BigInt> for BigInt {
918 fn shl(&self, rhs: &uint) -> BigInt {
919 BigInt::from_biguint(self.sign, self.data << *rhs)
923 impl Shr<uint, BigInt> for BigInt {
925 fn shr(&self, rhs: &uint) -> BigInt {
926 BigInt::from_biguint(self.sign, self.data >> *rhs)
930 impl Zero for BigInt {
932 fn zero() -> BigInt {
933 BigInt::from_biguint(Zero, Zero::zero())
937 fn is_zero(&self) -> bool { self.sign == Zero }
940 impl One for BigInt {
943 BigInt::from_biguint(Plus, One::one())
947 impl Signed for BigInt {
949 fn abs(&self) -> BigInt {
951 Plus | Zero => self.clone(),
952 Minus => BigInt::from_biguint(Plus, self.data.clone())
957 fn abs_sub(&self, other: &BigInt) -> BigInt {
958 if *self <= *other { Zero::zero() } else { *self - *other }
962 fn signum(&self) -> BigInt {
964 Plus => BigInt::from_biguint(Plus, One::one()),
965 Minus => BigInt::from_biguint(Minus, One::one()),
966 Zero => Zero::zero(),
971 fn is_positive(&self) -> bool { self.sign == Plus }
974 fn is_negative(&self) -> bool { self.sign == Minus }
977 impl Add<BigInt, BigInt> for BigInt {
979 fn add(&self, other: &BigInt) -> BigInt {
980 match (self.sign, other.sign) {
981 (Zero, _) => other.clone(),
982 (_, Zero) => self.clone(),
983 (Plus, Plus) => BigInt::from_biguint(Plus, self.data + other.data),
984 (Plus, Minus) => self - (-*other),
985 (Minus, Plus) => other - (-*self),
986 (Minus, Minus) => -((-self) + (-*other))
991 impl Sub<BigInt, BigInt> for BigInt {
993 fn sub(&self, other: &BigInt) -> BigInt {
994 match (self.sign, other.sign) {
996 (_, Zero) => self.clone(),
997 (Plus, Plus) => match self.data.cmp(&other.data) {
998 Less => BigInt::from_biguint(Minus, other.data - self.data),
999 Greater => BigInt::from_biguint(Plus, self.data - other.data),
1000 Equal => Zero::zero()
1002 (Plus, Minus) => self + (-*other),
1003 (Minus, Plus) => -((-self) + *other),
1004 (Minus, Minus) => (-other) - (-*self)
1009 impl Mul<BigInt, BigInt> for BigInt {
1011 fn mul(&self, other: &BigInt) -> BigInt {
1012 match (self.sign, other.sign) {
1013 (Zero, _) | (_, Zero) => Zero::zero(),
1014 (Plus, Plus) | (Minus, Minus) => {
1015 BigInt::from_biguint(Plus, self.data * other.data)
1017 (Plus, Minus) | (Minus, Plus) => {
1018 BigInt::from_biguint(Minus, self.data * other.data)
1024 impl Div<BigInt, BigInt> for BigInt {
1026 fn div(&self, other: &BigInt) -> BigInt {
1027 let (q, _) = self.div_rem(other);
1032 impl Rem<BigInt, BigInt> for BigInt {
1034 fn rem(&self, other: &BigInt) -> BigInt {
1035 let (_, r) = self.div_rem(other);
1040 impl Neg<BigInt> for BigInt {
1042 fn neg(&self) -> BigInt {
1043 BigInt::from_biguint(self.sign.neg(), self.data.clone())
1047 impl CheckedAdd for BigInt {
1049 fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
1050 return Some(self.add(v));
1054 impl CheckedSub for BigInt {
1056 fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
1057 return Some(self.sub(v));
1061 impl CheckedMul for BigInt {
1063 fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
1064 return Some(self.mul(v));
1068 impl CheckedDiv for BigInt {
1070 fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
1074 return Some(self.div(v));
1079 impl Integer for BigInt {
1081 fn div_rem(&self, other: &BigInt) -> (BigInt, BigInt) {
1082 // r.sign == self.sign
1083 let (d_ui, r_ui) = self.data.div_mod_floor(&other.data);
1084 let d = BigInt::from_biguint(Plus, d_ui);
1085 let r = BigInt::from_biguint(Plus, r_ui);
1086 match (self.sign, other.sign) {
1087 (_, Zero) => fail!(),
1088 (Plus, Plus) | (Zero, Plus) => ( d, r),
1089 (Plus, Minus) | (Zero, Minus) => (-d, r),
1090 (Minus, Plus) => (-d, -r),
1091 (Minus, Minus) => ( d, -r)
1096 fn div_floor(&self, other: &BigInt) -> BigInt {
1097 let (d, _) = self.div_mod_floor(other);
1102 fn mod_floor(&self, other: &BigInt) -> BigInt {
1103 let (_, m) = self.div_mod_floor(other);
1107 fn div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt) {
1108 // m.sign == other.sign
1109 let (d_ui, m_ui) = self.data.div_rem(&other.data);
1110 let d = BigInt::from_biguint(Plus, d_ui);
1111 let m = BigInt::from_biguint(Plus, m_ui);
1112 match (self.sign, other.sign) {
1113 (_, Zero) => fail!(),
1114 (Plus, Plus) | (Zero, Plus) => (d, m),
1115 (Plus, Minus) | (Zero, Minus) => if m.is_zero() {
1118 (-d - One::one(), m + *other)
1120 (Minus, Plus) => if m.is_zero() {
1123 (-d - One::one(), other - m)
1125 (Minus, Minus) => (d, -m)
1129 /// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
1131 /// The result is always positive.
1133 fn gcd(&self, other: &BigInt) -> BigInt {
1134 BigInt::from_biguint(Plus, self.data.gcd(&other.data))
1137 /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
1139 fn lcm(&self, other: &BigInt) -> BigInt {
1140 BigInt::from_biguint(Plus, self.data.lcm(&other.data))
1143 /// Deprecated, use `is_multiple_of` instead.
1144 #[deprecated = "function renamed to `is_multiple_of`"]
1146 fn divides(&self, other: &BigInt) -> bool { return self.is_multiple_of(other); }
1148 /// Returns `true` if the number is a multiple of `other`.
1150 fn is_multiple_of(&self, other: &BigInt) -> bool { self.data.is_multiple_of(&other.data) }
1152 /// Returns `true` if the number is divisible by `2`.
1154 fn is_even(&self) -> bool { self.data.is_even() }
1156 /// Returns `true` if the number is not divisible by `2`.
1158 fn is_odd(&self) -> bool { self.data.is_odd() }
1161 impl ToPrimitive for BigInt {
1163 fn to_i64(&self) -> Option<i64> {
1165 Plus => self.data.to_i64(),
1168 self.data.to_u64().and_then(|n| {
1169 let m: u64 = 1 << 63;
1183 fn to_u64(&self) -> Option<u64> {
1185 Plus => self.data.to_u64(),
1192 impl FromPrimitive for BigInt {
1194 fn from_i64(n: i64) -> Option<BigInt> {
1196 FromPrimitive::from_u64(n as u64).and_then(|n| {
1197 Some(BigInt::from_biguint(Plus, n))
1200 FromPrimitive::from_u64(u64::MAX - (n as u64) + 1).and_then(
1202 Some(BigInt::from_biguint(Minus, n))
1210 fn from_u64(n: u64) -> Option<BigInt> {
1214 FromPrimitive::from_u64(n).and_then(|n| {
1215 Some(BigInt::from_biguint(Plus, n))
1221 /// A generic trait for converting a value to a `BigInt`.
1222 pub trait ToBigInt {
1223 /// Converts the value of `self` to a `BigInt`.
1224 fn to_bigint(&self) -> Option<BigInt>;
1227 impl ToBigInt for BigInt {
1229 fn to_bigint(&self) -> Option<BigInt> {
1234 impl ToBigInt for BigUint {
1236 fn to_bigint(&self) -> Option<BigInt> {
1240 Some(BigInt { sign: Plus, data: self.clone() })
1245 macro_rules! impl_to_bigint(
1246 ($T:ty, $from_ty:path) => {
1247 impl ToBigInt for $T {
1249 fn to_bigint(&self) -> Option<BigInt> {
1256 impl_to_bigint!(int, FromPrimitive::from_int)
1257 impl_to_bigint!(i8, FromPrimitive::from_i8)
1258 impl_to_bigint!(i16, FromPrimitive::from_i16)
1259 impl_to_bigint!(i32, FromPrimitive::from_i32)
1260 impl_to_bigint!(i64, FromPrimitive::from_i64)
1261 impl_to_bigint!(uint, FromPrimitive::from_uint)
1262 impl_to_bigint!(u8, FromPrimitive::from_u8)
1263 impl_to_bigint!(u16, FromPrimitive::from_u16)
1264 impl_to_bigint!(u32, FromPrimitive::from_u32)
1265 impl_to_bigint!(u64, FromPrimitive::from_u64)
1267 impl ToStrRadix for BigInt {
1269 fn to_str_radix(&self, radix: uint) -> String {
1271 Plus => self.data.to_str_radix(radix),
1272 Zero => "0".to_string(),
1273 Minus => format!("-{}", self.data.to_str_radix(radix)),
1278 impl FromStrRadix for BigInt {
1279 /// Creates and initializes a BigInt.
1281 fn from_str_radix(s: &str, radix: uint) -> Option<BigInt> {
1282 BigInt::parse_bytes(s.as_bytes(), radix)
1286 pub trait RandBigInt {
1287 /// Generate a random `BigUint` of the given bit size.
1288 fn gen_biguint(&mut self, bit_size: uint) -> BigUint;
1290 /// Generate a random BigInt of the given bit size.
1291 fn gen_bigint(&mut self, bit_size: uint) -> BigInt;
1293 /// Generate a random `BigUint` less than the given bound. Fails
1294 /// when the bound is zero.
1295 fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint;
1297 /// Generate a random `BigUint` within the given range. The lower
1298 /// bound is inclusive; the upper bound is exclusive. Fails when
1299 /// the upper bound is not greater than the lower bound.
1300 fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint;
1302 /// Generate a random `BigInt` within the given range. The lower
1303 /// bound is inclusive; the upper bound is exclusive. Fails when
1304 /// the upper bound is not greater than the lower bound.
1305 fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt;
1308 impl<R: Rng> RandBigInt for R {
1309 fn gen_biguint(&mut self, bit_size: uint) -> BigUint {
1310 let (digits, rem) = bit_size.div_rem(&BigDigit::bits);
1311 let mut data = Vec::with_capacity(digits+1);
1312 for _ in range(0, digits) {
1313 data.push(self.gen());
1316 let final_digit: BigDigit = self.gen();
1317 data.push(final_digit >> (BigDigit::bits - rem));
1322 fn gen_bigint(&mut self, bit_size: uint) -> BigInt {
1323 // Generate a random BigUint...
1324 let biguint = self.gen_biguint(bit_size);
1325 // ...and then randomly assign it a Sign...
1326 let sign = if biguint.is_zero() {
1327 // ...except that if the BigUint is zero, we need to try
1328 // again with probability 0.5. This is because otherwise,
1329 // the probability of generating a zero BigInt would be
1330 // double that of any other number.
1332 return self.gen_bigint(bit_size);
1336 } else if self.gen() {
1341 BigInt::from_biguint(sign, biguint)
1344 fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint {
1345 assert!(!bound.is_zero());
1346 let bits = bound.bits();
1348 let n = self.gen_biguint(bits);
1349 if n < *bound { return n; }
1353 fn gen_biguint_range(&mut self,
1357 assert!(*lbound < *ubound);
1358 return *lbound + self.gen_biguint_below(&(*ubound - *lbound));
1361 fn gen_bigint_range(&mut self,
1365 assert!(*lbound < *ubound);
1366 let delta = (*ubound - *lbound).to_biguint().unwrap();
1367 return *lbound + self.gen_biguint_below(&delta).to_bigint().unwrap();
1372 /// Creates and initializes a BigInt.
1374 /// The digits are be in base 2^32.
1376 pub fn new(sign: Sign, digits: Vec<BigDigit>) -> BigInt {
1377 BigInt::from_biguint(sign, BigUint::new(digits))
1380 /// Creates and initializes a `BigInt`.
1382 /// The digits are be in base 2^32.
1384 pub fn from_biguint(sign: Sign, data: BigUint) -> BigInt {
1385 if sign == Zero || data.is_zero() {
1386 return BigInt { sign: Zero, data: Zero::zero() };
1388 BigInt { sign: sign, data: data }
1391 /// Creates and initializes a `BigInt`.
1393 pub fn from_slice(sign: Sign, slice: &[BigDigit]) -> BigInt {
1394 BigInt::from_biguint(sign, BigUint::from_slice(slice))
1397 /// Creates and initializes a `BigInt`.
1398 pub fn parse_bytes(buf: &[u8], radix: uint) -> Option<BigInt> {
1399 if buf.is_empty() { return None; }
1400 let mut sign = Plus;
1406 return BigUint::parse_bytes(buf.slice(start, buf.len()), radix)
1407 .map(|bu| BigInt::from_biguint(sign, bu));
1410 /// Converts this `BigInt` into a `BigUint`, if it's not negative.
1412 pub fn to_biguint(&self) -> Option<BigUint> {
1414 Plus => Some(self.data.clone()),
1415 Zero => Some(Zero::zero()),
1424 use super::{BigDigit, BigUint, ToBigUint};
1425 use super::{Plus, BigInt, RandBigInt, ToBigInt};
1427 use std::cmp::{Less, Equal, Greater};
1428 use std::from_str::FromStr;
1430 use std::num::{Zero, One, FromStrRadix, ToStrRadix};
1431 use std::num::{ToPrimitive, FromPrimitive};
1432 use std::num::CheckedDiv;
1433 use std::rand::task_rng;
1435 use std::hash::hash;
1438 fn test_from_slice() {
1439 fn check(slice: &[BigDigit], data: &[BigDigit]) {
1440 assert!(data == BigUint::from_slice(slice).data.as_slice());
1443 check([0, 0, 0], []);
1444 check([1, 2, 0, 0], [1, 2]);
1445 check([0, 0, 1, 2], [0, 0, 1, 2]);
1446 check([0, 0, 1, 2, 0, 0], [0, 0, 1, 2]);
1452 let data: [&[_], ..7] = [ &[], &[1], &[2], &[-1], &[0, 1], &[2, 1], &[1, 1, 1] ];
1453 let data: Vec<BigUint> = data.iter().map(|v| BigUint::from_slice(*v)).collect();
1454 for (i, ni) in data.iter().enumerate() {
1455 for (j0, nj) in data.slice(i, data.len()).iter().enumerate() {
1458 assert_eq!(ni.cmp(nj), Equal);
1459 assert_eq!(nj.cmp(ni), Equal);
1461 assert!(!(ni != nj));
1464 assert!(!(ni < nj));
1465 assert!(!(ni > nj));
1467 assert_eq!(ni.cmp(nj), Less);
1468 assert_eq!(nj.cmp(ni), Greater);
1470 assert!(!(ni == nj));
1474 assert!(!(ni >= nj));
1476 assert!(!(ni > nj));
1478 assert!(!(nj <= ni));
1480 assert!(!(nj < ni));
1489 let a = BigUint::new(vec!());
1490 let b = BigUint::new(vec!(0));
1491 let c = BigUint::new(vec!(1));
1492 let d = BigUint::new(vec!(1,0,0,0,0,0));
1493 let e = BigUint::new(vec!(0,0,0,0,0,1));
1494 assert!(hash(&a) == hash(&b));
1495 assert!(hash(&b) != hash(&c));
1496 assert!(hash(&c) == hash(&d));
1497 assert!(hash(&d) != hash(&e));
1502 fn check(left: &[BigDigit],
1504 expected: &[BigDigit]) {
1505 assert_eq!(BigUint::from_slice(left) & BigUint::from_slice(right),
1506 BigUint::from_slice(expected));
1509 check([268, 482, 17],
1516 fn check(left: &[BigDigit],
1518 expected: &[BigDigit]) {
1519 assert_eq!(BigUint::from_slice(left) | BigUint::from_slice(right),
1520 BigUint::from_slice(expected));
1523 check([268, 482, 17],
1530 fn check(left: &[BigDigit],
1532 expected: &[BigDigit]) {
1533 assert_eq!(BigUint::from_slice(left) ^ BigUint::from_slice(right),
1534 BigUint::from_slice(expected));
1537 check([268, 482, 17],
1544 fn check(s: &str, shift: uint, ans: &str) {
1545 let opt_biguint: Option<BigUint> = FromStrRadix::from_str_radix(s, 16);
1546 let bu = (opt_biguint.unwrap() << shift).to_str_radix(16);
1547 assert_eq!(bu.as_slice(), ans);
1659 check("88887777666655554444333322221111", 16,
1660 "888877776666555544443333222211110000");
1665 fn check(s: &str, shift: uint, ans: &str) {
1666 let opt_biguint: Option<BigUint> =
1667 FromStrRadix::from_str_radix(s, 16);
1668 let bu = (opt_biguint.unwrap() >> shift).to_str_radix(16);
1669 assert_eq!(bu.as_slice(), ans);
1777 check("888877776666555544443333222211110000", 16,
1778 "88887777666655554444333322221111");
1781 // `DoubleBigDigit` size dependent
1783 fn test_convert_i64() {
1784 fn check(b1: BigUint, i: i64) {
1785 let b2: BigUint = FromPrimitive::from_i64(i).unwrap();
1787 assert!(b1.to_i64().unwrap() == i);
1790 check(Zero::zero(), 0);
1791 check(One::one(), 1);
1792 check(i64::MAX.to_biguint().unwrap(), i64::MAX);
1794 check(BigUint::new(vec!( )), 0);
1795 check(BigUint::new(vec!( 1 )), (1 << (0*BigDigit::bits)));
1796 check(BigUint::new(vec!(-1 )), (1 << (1*BigDigit::bits)) - 1);
1797 check(BigUint::new(vec!( 0, 1 )), (1 << (1*BigDigit::bits)));
1798 check(BigUint::new(vec!(-1, -1 >> 1)), i64::MAX);
1800 assert_eq!(i64::MIN.to_biguint(), None);
1801 assert_eq!(BigUint::new(vec!(-1, -1 )).to_i64(), None);
1802 assert_eq!(BigUint::new(vec!( 0, 0, 1)).to_i64(), None);
1803 assert_eq!(BigUint::new(vec!(-1, -1, -1)).to_i64(), None);
1806 // `DoubleBigDigit` size dependent
1808 fn test_convert_u64() {
1809 fn check(b1: BigUint, u: u64) {
1810 let b2: BigUint = FromPrimitive::from_u64(u).unwrap();
1812 assert!(b1.to_u64().unwrap() == u);
1815 check(Zero::zero(), 0);
1816 check(One::one(), 1);
1817 check(u64::MIN.to_biguint().unwrap(), u64::MIN);
1818 check(u64::MAX.to_biguint().unwrap(), u64::MAX);
1820 check(BigUint::new(vec!( )), 0);
1821 check(BigUint::new(vec!( 1 )), (1 << (0*BigDigit::bits)));
1822 check(BigUint::new(vec!(-1 )), (1 << (1*BigDigit::bits)) - 1);
1823 check(BigUint::new(vec!( 0, 1)), (1 << (1*BigDigit::bits)));
1824 check(BigUint::new(vec!(-1, -1)), u64::MAX);
1826 assert_eq!(BigUint::new(vec!( 0, 0, 1)).to_u64(), None);
1827 assert_eq!(BigUint::new(vec!(-1, -1, -1)).to_u64(), None);
1831 fn test_convert_to_bigint() {
1832 fn check(n: BigUint, ans: BigInt) {
1833 assert_eq!(n.to_bigint().unwrap(), ans);
1834 assert_eq!(n.to_bigint().unwrap().to_biguint().unwrap(), n);
1836 check(Zero::zero(), Zero::zero());
1837 check(BigUint::new(vec!(1,2,3)),
1838 BigInt::from_biguint(Plus, BigUint::new(vec!(1,2,3))));
1841 static sum_triples: &'static [(&'static [BigDigit],
1842 &'static [BigDigit],
1843 &'static [BigDigit])] = &[
1845 (&[], &[ 1], &[ 1]),
1846 (&[ 1], &[ 1], &[ 2]),
1847 (&[ 1], &[ 1, 1], &[ 2, 1]),
1848 (&[ 1], &[-1], &[ 0, 1]),
1849 (&[ 1], &[-1, -1], &[ 0, 0, 1]),
1850 (&[-1, -1], &[-1, -1], &[-2, -1, 1]),
1851 (&[ 1, 1, 1], &[-1, -1], &[ 0, 1, 2]),
1852 (&[ 2, 2, 1], &[-1, -2], &[ 1, 1, 2])
1857 for elm in sum_triples.iter() {
1858 let (a_vec, b_vec, c_vec) = *elm;
1859 let a = BigUint::from_slice(a_vec);
1860 let b = BigUint::from_slice(b_vec);
1861 let c = BigUint::from_slice(c_vec);
1863 assert!(a + b == c);
1864 assert!(b + a == c);
1870 for elm in sum_triples.iter() {
1871 let (a_vec, b_vec, c_vec) = *elm;
1872 let a = BigUint::from_slice(a_vec);
1873 let b = BigUint::from_slice(b_vec);
1874 let c = BigUint::from_slice(c_vec);
1876 assert!(c - a == b);
1877 assert!(c - b == a);
1883 fn test_sub_fail_on_underflow() {
1884 let (a, b) : (BigUint, BigUint) = (Zero::zero(), One::one());
1888 static mul_triples: &'static [(&'static [BigDigit],
1889 &'static [BigDigit],
1890 &'static [BigDigit])] = &[
1894 (&[ 1], &[ 1], &[1]),
1895 (&[ 2], &[ 3], &[ 6]),
1896 (&[ 1], &[ 1, 1, 1], &[1, 1, 1]),
1897 (&[ 1, 2, 3], &[ 3], &[ 3, 6, 9]),
1898 (&[ 1, 1, 1], &[-1], &[-1, -1, -1]),
1899 (&[ 1, 2, 3], &[-1], &[-1, -2, -2, 2]),
1900 (&[ 1, 2, 3, 4], &[-1], &[-1, -2, -2, -2, 3]),
1901 (&[-1], &[-1], &[ 1, -2]),
1902 (&[-1, -1], &[-1], &[ 1, -1, -2]),
1903 (&[-1, -1, -1], &[-1], &[ 1, -1, -1, -2]),
1904 (&[-1, -1, -1, -1], &[-1], &[ 1, -1, -1, -1, -2]),
1905 (&[-1/2 + 1], &[ 2], &[ 0, 1]),
1906 (&[0, -1/2 + 1], &[ 2], &[ 0, 0, 1]),
1907 (&[ 1, 2], &[ 1, 2, 3], &[1, 4, 7, 6]),
1908 (&[-1, -1], &[-1, -1, -1], &[1, 0, -1, -2, -1]),
1909 (&[-1, -1, -1], &[-1, -1, -1, -1], &[1, 0, 0, -1, -2, -1, -1]),
1910 (&[ 0, 0, 1], &[ 1, 2, 3], &[0, 0, 1, 2, 3]),
1911 (&[ 0, 0, 1], &[ 0, 0, 0, 1], &[0, 0, 0, 0, 0, 1])
1914 static div_rem_quadruples: &'static [(&'static [BigDigit],
1915 &'static [BigDigit],
1916 &'static [BigDigit],
1917 &'static [BigDigit])]
1919 (&[ 1], &[ 2], &[], &[1]),
1920 (&[ 1, 1], &[ 2], &[-1/2+1], &[1]),
1921 (&[ 1, 1, 1], &[ 2], &[-1/2+1, -1/2+1], &[1]),
1922 (&[ 0, 1], &[-1], &[1], &[1]),
1923 (&[-1, -1], &[-2], &[2, 1], &[3])
1928 for elm in mul_triples.iter() {
1929 let (a_vec, b_vec, c_vec) = *elm;
1930 let a = BigUint::from_slice(a_vec);
1931 let b = BigUint::from_slice(b_vec);
1932 let c = BigUint::from_slice(c_vec);
1934 assert!(a * b == c);
1935 assert!(b * a == c);
1938 for elm in div_rem_quadruples.iter() {
1939 let (a_vec, b_vec, c_vec, d_vec) = *elm;
1940 let a = BigUint::from_slice(a_vec);
1941 let b = BigUint::from_slice(b_vec);
1942 let c = BigUint::from_slice(c_vec);
1943 let d = BigUint::from_slice(d_vec);
1945 assert!(a == b * c + d);
1946 assert!(a == c * b + d);
1952 for elm in mul_triples.iter() {
1953 let (a_vec, b_vec, c_vec) = *elm;
1954 let a = BigUint::from_slice(a_vec);
1955 let b = BigUint::from_slice(b_vec);
1956 let c = BigUint::from_slice(c_vec);
1959 assert_eq!(c.div_rem(&a), (b.clone(), Zero::zero()));
1962 assert_eq!(c.div_rem(&b), (a.clone(), Zero::zero()));
1966 for elm in div_rem_quadruples.iter() {
1967 let (a_vec, b_vec, c_vec, d_vec) = *elm;
1968 let a = BigUint::from_slice(a_vec);
1969 let b = BigUint::from_slice(b_vec);
1970 let c = BigUint::from_slice(c_vec);
1971 let d = BigUint::from_slice(d_vec);
1973 if !b.is_zero() { assert!(a.div_rem(&b) == (c, d)); }
1978 fn test_checked_add() {
1979 for elm in sum_triples.iter() {
1980 let (aVec, bVec, cVec) = *elm;
1981 let a = BigUint::from_slice(aVec);
1982 let b = BigUint::from_slice(bVec);
1983 let c = BigUint::from_slice(cVec);
1985 assert!(a.checked_add(&b).unwrap() == c);
1986 assert!(b.checked_add(&a).unwrap() == c);
1991 fn test_checked_sub() {
1992 for elm in sum_triples.iter() {
1993 let (aVec, bVec, cVec) = *elm;
1994 let a = BigUint::from_slice(aVec);
1995 let b = BigUint::from_slice(bVec);
1996 let c = BigUint::from_slice(cVec);
1998 assert!(c.checked_sub(&a).unwrap() == b);
1999 assert!(c.checked_sub(&b).unwrap() == a);
2002 assert!(a.checked_sub(&c).is_none());
2005 assert!(b.checked_sub(&c).is_none());
2011 fn test_checked_mul() {
2012 for elm in mul_triples.iter() {
2013 let (aVec, bVec, cVec) = *elm;
2014 let a = BigUint::from_slice(aVec);
2015 let b = BigUint::from_slice(bVec);
2016 let c = BigUint::from_slice(cVec);
2018 assert!(a.checked_mul(&b).unwrap() == c);
2019 assert!(b.checked_mul(&a).unwrap() == c);
2022 for elm in div_rem_quadruples.iter() {
2023 let (aVec, bVec, cVec, dVec) = *elm;
2024 let a = BigUint::from_slice(aVec);
2025 let b = BigUint::from_slice(bVec);
2026 let c = BigUint::from_slice(cVec);
2027 let d = BigUint::from_slice(dVec);
2029 assert!(a == b.checked_mul(&c).unwrap() + d);
2030 assert!(a == c.checked_mul(&b).unwrap() + d);
2035 fn test_checked_div() {
2036 for elm in mul_triples.iter() {
2037 let (aVec, bVec, cVec) = *elm;
2038 let a = BigUint::from_slice(aVec);
2039 let b = BigUint::from_slice(bVec);
2040 let c = BigUint::from_slice(cVec);
2043 assert!(c.checked_div(&a).unwrap() == b);
2046 assert!(c.checked_div(&b).unwrap() == a);
2049 assert!(c.checked_div(&Zero::zero()).is_none());
2055 fn check(a: uint, b: uint, c: uint) {
2056 let big_a: BigUint = FromPrimitive::from_uint(a).unwrap();
2057 let big_b: BigUint = FromPrimitive::from_uint(b).unwrap();
2058 let big_c: BigUint = FromPrimitive::from_uint(c).unwrap();
2060 assert_eq!(big_a.gcd(&big_b), big_c);
2072 fn check(a: uint, b: uint, c: uint) {
2073 let big_a: BigUint = FromPrimitive::from_uint(a).unwrap();
2074 let big_b: BigUint = FromPrimitive::from_uint(b).unwrap();
2075 let big_c: BigUint = FromPrimitive::from_uint(c).unwrap();
2077 assert_eq!(big_a.lcm(&big_b), big_c);
2085 check(99, 17, 1683);
2090 let one: BigUint = FromStr::from_str("1").unwrap();
2091 let two: BigUint = FromStr::from_str("2").unwrap();
2092 let thousand: BigUint = FromStr::from_str("1000").unwrap();
2093 let big: BigUint = FromStr::from_str("1000000000000000000000").unwrap();
2094 let bigger: BigUint = FromStr::from_str("1000000000000000000001").unwrap();
2095 assert!(one.is_odd());
2096 assert!(two.is_even());
2097 assert!(thousand.is_even());
2098 assert!(big.is_even());
2099 assert!(bigger.is_odd());
2100 assert!((one << 64).is_even());
2101 assert!(((one << 64) + one).is_odd());
2104 fn to_str_pairs() -> Vec<(BigUint, Vec<(uint, String)>)> {
2105 let bits = BigDigit::bits;
2106 vec!(( Zero::zero(), vec!(
2107 (2, "0".to_string()), (3, "0".to_string())
2108 )), ( BigUint::from_slice([ 0xff ]), vec!(
2109 (2, "11111111".to_string()),
2110 (3, "100110".to_string()),
2111 (4, "3333".to_string()),
2112 (5, "2010".to_string()),
2113 (6, "1103".to_string()),
2114 (7, "513".to_string()),
2115 (8, "377".to_string()),
2116 (9, "313".to_string()),
2117 (10, "255".to_string()),
2118 (11, "212".to_string()),
2119 (12, "193".to_string()),
2120 (13, "168".to_string()),
2121 (14, "143".to_string()),
2122 (15, "120".to_string()),
2123 (16, "ff".to_string())
2124 )), ( BigUint::from_slice([ 0xfff ]), vec!(
2125 (2, "111111111111".to_string()),
2126 (4, "333333".to_string()),
2127 (16, "fff".to_string())
2128 )), ( BigUint::from_slice([ 1, 2 ]), vec!(
2130 format!("10{}1", "0".repeat(bits - 1))),
2132 format!("2{}1", "0".repeat(bits / 2 - 1))),
2134 32 => "8589934593".to_string(),
2135 16 => "131073".to_string(),
2139 format!("2{}1", "0".repeat(bits / 4 - 1)))
2140 )), ( BigUint::from_slice([ 1, 2, 3 ]), vec!(
2142 format!("11{}10{}1",
2143 "0".repeat(bits - 2),
2144 "0".repeat(bits - 1))),
2147 "0".repeat(bits / 2 - 1),
2148 "0".repeat(bits / 2 - 1))),
2150 32 => "55340232229718589441".to_string(),
2151 16 => "12885032961".to_string(),
2156 "0".repeat(bits / 4 - 1),
2157 "0".repeat(bits / 4 - 1)))
2162 fn test_to_str_radix() {
2163 let r = to_str_pairs();
2164 for num_pair in r.iter() {
2165 let &(ref n, ref rs) = num_pair;
2166 for str_pair in rs.iter() {
2167 let &(ref radix, ref str) = str_pair;
2168 assert_eq!(n.to_str_radix(*radix).as_slice(),
2175 fn test_from_str_radix() {
2176 let r = to_str_pairs();
2177 for num_pair in r.iter() {
2178 let &(ref n, ref rs) = num_pair;
2179 for str_pair in rs.iter() {
2180 let &(ref radix, ref str) = str_pair;
2182 &FromStrRadix::from_str_radix(str.as_slice(),
2187 let zed: Option<BigUint> = FromStrRadix::from_str_radix("Z", 10);
2188 assert_eq!(zed, None);
2189 let blank: Option<BigUint> = FromStrRadix::from_str_radix("_", 2);
2190 assert_eq!(blank, None);
2191 let minus_one: Option<BigUint> = FromStrRadix::from_str_radix("-1",
2193 assert_eq!(minus_one, None);
2198 fn factor(n: uint) -> BigUint {
2199 let mut f: BigUint = One::one();
2200 for i in range(2, n + 1) {
2201 // FIXME(#5992): assignment operator overloads
2202 // f *= FromPrimitive::from_uint(i);
2203 f = f * FromPrimitive::from_uint(i).unwrap();
2208 fn check(n: uint, s: &str) {
2210 let ans = match FromStrRadix::from_str_radix(s, 10) {
2211 Some(x) => x, None => fail!()
2217 check(10, "3628800");
2218 check(20, "2432902008176640000");
2219 check(30, "265252859812191058636308480000000");
2224 assert_eq!(BigUint::new(vec!(0,0,0,0)).bits(), 0);
2225 let n: BigUint = FromPrimitive::from_uint(0).unwrap();
2226 assert_eq!(n.bits(), 0);
2227 let n: BigUint = FromPrimitive::from_uint(1).unwrap();
2228 assert_eq!(n.bits(), 1);
2229 let n: BigUint = FromPrimitive::from_uint(3).unwrap();
2230 assert_eq!(n.bits(), 2);
2231 let n: BigUint = FromStrRadix::from_str_radix("4000000000", 16).unwrap();
2232 assert_eq!(n.bits(), 39);
2233 let one: BigUint = One::one();
2234 assert_eq!((one << 426).bits(), 427);
2239 let mut rng = task_rng();
2240 let _n: BigUint = rng.gen_biguint(137);
2241 assert!(rng.gen_biguint(0).is_zero());
2245 fn test_rand_range() {
2246 let mut rng = task_rng();
2248 for _ in range(0u, 10) {
2249 assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_uint(236).unwrap(),
2250 &FromPrimitive::from_uint(237).unwrap()),
2251 FromPrimitive::from_uint(236).unwrap());
2254 let l = FromPrimitive::from_uint(403469000 + 2352).unwrap();
2255 let u = FromPrimitive::from_uint(403469000 + 3513).unwrap();
2256 for _ in range(0u, 1000) {
2257 let n: BigUint = rng.gen_biguint_below(&u);
2260 let n: BigUint = rng.gen_biguint_range(&l, &u);
2268 fn test_zero_rand_range() {
2269 task_rng().gen_biguint_range(&FromPrimitive::from_uint(54).unwrap(),
2270 &FromPrimitive::from_uint(54).unwrap());
2275 fn test_negative_rand_range() {
2276 let mut rng = task_rng();
2277 let l = FromPrimitive::from_uint(2352).unwrap();
2278 let u = FromPrimitive::from_uint(3513).unwrap();
2279 // Switching u and l should fail:
2280 let _n: BigUint = rng.gen_biguint_range(&u, &l);
2287 use super::{BigDigit, BigUint, ToBigUint};
2288 use super::{Sign, Minus, Zero, Plus, BigInt, RandBigInt, ToBigInt};
2290 use std::cmp::{Less, Equal, Greater};
2292 use std::num::CheckedDiv;
2293 use std::num::{Zero, One, FromStrRadix, ToStrRadix};
2294 use std::num::{ToPrimitive, FromPrimitive};
2295 use std::rand::task_rng;
2297 use std::hash::hash;
2300 fn test_from_biguint() {
2301 fn check(inp_s: Sign, inp_n: uint, ans_s: Sign, ans_n: uint) {
2302 let inp = BigInt::from_biguint(inp_s, FromPrimitive::from_uint(inp_n).unwrap());
2303 let ans = BigInt { sign: ans_s, data: FromPrimitive::from_uint(ans_n).unwrap()};
2304 assert_eq!(inp, ans);
2306 check(Plus, 1, Plus, 1);
2307 check(Plus, 0, Zero, 0);
2308 check(Minus, 1, Minus, 1);
2309 check(Zero, 1, Zero, 0);
2314 let vs: [&[BigDigit], ..4] = [ &[2 as BigDigit], &[1, 1], &[2, 1], &[1, 1, 1] ];
2315 let mut nums = Vec::new();
2316 for s in vs.iter().rev() {
2317 nums.push(BigInt::from_slice(Minus, *s));
2319 nums.push(Zero::zero());
2320 nums.extend(vs.iter().map(|s| BigInt::from_slice(Plus, *s)));
2322 for (i, ni) in nums.iter().enumerate() {
2323 for (j0, nj) in nums.slice(i, nums.len()).iter().enumerate() {
2326 assert_eq!(ni.cmp(nj), Equal);
2327 assert_eq!(nj.cmp(ni), Equal);
2329 assert!(!(ni != nj));
2332 assert!(!(ni < nj));
2333 assert!(!(ni > nj));
2335 assert_eq!(ni.cmp(nj), Less);
2336 assert_eq!(nj.cmp(ni), Greater);
2338 assert!(!(ni == nj));
2342 assert!(!(ni >= nj));
2344 assert!(!(ni > nj));
2346 assert!(!(nj <= ni));
2348 assert!(!(nj < ni));
2357 let a = BigInt::new(Zero, vec!());
2358 let b = BigInt::new(Zero, vec!(0));
2359 let c = BigInt::new(Plus, vec!(1));
2360 let d = BigInt::new(Plus, vec!(1,0,0,0,0,0));
2361 let e = BigInt::new(Plus, vec!(0,0,0,0,0,1));
2362 let f = BigInt::new(Minus, vec!(1));
2363 assert!(hash(&a) == hash(&b));
2364 assert!(hash(&b) != hash(&c));
2365 assert!(hash(&c) == hash(&d));
2366 assert!(hash(&d) != hash(&e));
2367 assert!(hash(&c) != hash(&f));
2371 fn test_convert_i64() {
2372 fn check(b1: BigInt, i: i64) {
2373 let b2: BigInt = FromPrimitive::from_i64(i).unwrap();
2375 assert!(b1.to_i64().unwrap() == i);
2378 check(Zero::zero(), 0);
2379 check(One::one(), 1);
2380 check(i64::MIN.to_bigint().unwrap(), i64::MIN);
2381 check(i64::MAX.to_bigint().unwrap(), i64::MAX);
2384 (i64::MAX as u64 + 1).to_bigint().unwrap().to_i64(),
2388 BigInt::from_biguint(Plus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_i64(),
2392 BigInt::from_biguint(Minus, BigUint::new(vec!(1,0,0,1<<(BigDigit::bits-1)))).to_i64(),
2396 BigInt::from_biguint(Minus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_i64(),
2401 fn test_convert_u64() {
2402 fn check(b1: BigInt, u: u64) {
2403 let b2: BigInt = FromPrimitive::from_u64(u).unwrap();
2405 assert!(b1.to_u64().unwrap() == u);
2408 check(Zero::zero(), 0);
2409 check(One::one(), 1);
2410 check(u64::MIN.to_bigint().unwrap(), u64::MIN);
2411 check(u64::MAX.to_bigint().unwrap(), u64::MAX);
2414 BigInt::from_biguint(Plus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_u64(),
2417 let max_value: BigUint = FromPrimitive::from_u64(u64::MAX).unwrap();
2418 assert_eq!(BigInt::from_biguint(Minus, max_value).to_u64(), None);
2419 assert_eq!(BigInt::from_biguint(Minus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_u64(), None);
2423 fn test_convert_to_biguint() {
2424 fn check(n: BigInt, ans_1: BigUint) {
2425 assert_eq!(n.to_biguint().unwrap(), ans_1);
2426 assert_eq!(n.to_biguint().unwrap().to_bigint().unwrap(), n);
2428 let zero: BigInt = Zero::zero();
2429 let unsigned_zero: BigUint = Zero::zero();
2430 let positive = BigInt::from_biguint(
2431 Plus, BigUint::new(vec!(1,2,3)));
2432 let negative = -positive;
2434 check(zero, unsigned_zero);
2435 check(positive, BigUint::new(vec!(1,2,3)));
2437 assert_eq!(negative.to_biguint(), None);
2440 static sum_triples: &'static [(&'static [BigDigit],
2441 &'static [BigDigit],
2442 &'static [BigDigit])] = &[
2444 (&[], &[ 1], &[ 1]),
2445 (&[ 1], &[ 1], &[ 2]),
2446 (&[ 1], &[ 1, 1], &[ 2, 1]),
2447 (&[ 1], &[-1], &[ 0, 1]),
2448 (&[ 1], &[-1, -1], &[ 0, 0, 1]),
2449 (&[-1, -1], &[-1, -1], &[-2, -1, 1]),
2450 (&[ 1, 1, 1], &[-1, -1], &[ 0, 1, 2]),
2451 (&[ 2, 2, 1], &[-1, -2], &[ 1, 1, 2])
2456 for elm in sum_triples.iter() {
2457 let (a_vec, b_vec, c_vec) = *elm;
2458 let a = BigInt::from_slice(Plus, a_vec);
2459 let b = BigInt::from_slice(Plus, b_vec);
2460 let c = BigInt::from_slice(Plus, c_vec);
2462 assert!(a + b == c);
2463 assert!(b + a == c);
2464 assert!(c + (-a) == b);
2465 assert!(c + (-b) == a);
2466 assert!(a + (-c) == (-b));
2467 assert!(b + (-c) == (-a));
2468 assert!((-a) + (-b) == (-c))
2469 assert!(a + (-a) == Zero::zero());
2475 for elm in sum_triples.iter() {
2476 let (a_vec, b_vec, c_vec) = *elm;
2477 let a = BigInt::from_slice(Plus, a_vec);
2478 let b = BigInt::from_slice(Plus, b_vec);
2479 let c = BigInt::from_slice(Plus, c_vec);
2481 assert!(c - a == b);
2482 assert!(c - b == a);
2483 assert!((-b) - a == (-c))
2484 assert!((-a) - b == (-c))
2485 assert!(b - (-a) == c);
2486 assert!(a - (-b) == c);
2487 assert!((-c) - (-a) == (-b));
2488 assert!(a - a == Zero::zero());
2492 static mul_triples: &'static [(&'static [BigDigit],
2493 &'static [BigDigit],
2494 &'static [BigDigit])] = &[
2498 (&[ 1], &[ 1], &[1]),
2499 (&[ 2], &[ 3], &[ 6]),
2500 (&[ 1], &[ 1, 1, 1], &[1, 1, 1]),
2501 (&[ 1, 2, 3], &[ 3], &[ 3, 6, 9]),
2502 (&[ 1, 1, 1], &[-1], &[-1, -1, -1]),
2503 (&[ 1, 2, 3], &[-1], &[-1, -2, -2, 2]),
2504 (&[ 1, 2, 3, 4], &[-1], &[-1, -2, -2, -2, 3]),
2505 (&[-1], &[-1], &[ 1, -2]),
2506 (&[-1, -1], &[-1], &[ 1, -1, -2]),
2507 (&[-1, -1, -1], &[-1], &[ 1, -1, -1, -2]),
2508 (&[-1, -1, -1, -1], &[-1], &[ 1, -1, -1, -1, -2]),
2509 (&[-1/2 + 1], &[ 2], &[ 0, 1]),
2510 (&[0, -1/2 + 1], &[ 2], &[ 0, 0, 1]),
2511 (&[ 1, 2], &[ 1, 2, 3], &[1, 4, 7, 6]),
2512 (&[-1, -1], &[-1, -1, -1], &[1, 0, -1, -2, -1]),
2513 (&[-1, -1, -1], &[-1, -1, -1, -1], &[1, 0, 0, -1, -2, -1, -1]),
2514 (&[ 0, 0, 1], &[ 1, 2, 3], &[0, 0, 1, 2, 3]),
2515 (&[ 0, 0, 1], &[ 0, 0, 0, 1], &[0, 0, 0, 0, 0, 1])
2518 static div_rem_quadruples: &'static [(&'static [BigDigit],
2519 &'static [BigDigit],
2520 &'static [BigDigit],
2521 &'static [BigDigit])]
2523 (&[ 1], &[ 2], &[], &[1]),
2524 (&[ 1, 1], &[ 2], &[-1/2+1], &[1]),
2525 (&[ 1, 1, 1], &[ 2], &[-1/2+1, -1/2+1], &[1]),
2526 (&[ 0, 1], &[-1], &[1], &[1]),
2527 (&[-1, -1], &[-2], &[2, 1], &[3])
2532 for elm in mul_triples.iter() {
2533 let (a_vec, b_vec, c_vec) = *elm;
2534 let a = BigInt::from_slice(Plus, a_vec);
2535 let b = BigInt::from_slice(Plus, b_vec);
2536 let c = BigInt::from_slice(Plus, c_vec);
2538 assert!(a * b == c);
2539 assert!(b * a == c);
2541 assert!((-a) * b == -c);
2542 assert!((-b) * a == -c);
2545 for elm in div_rem_quadruples.iter() {
2546 let (a_vec, b_vec, c_vec, d_vec) = *elm;
2547 let a = BigInt::from_slice(Plus, a_vec);
2548 let b = BigInt::from_slice(Plus, b_vec);
2549 let c = BigInt::from_slice(Plus, c_vec);
2550 let d = BigInt::from_slice(Plus, d_vec);
2552 assert!(a == b * c + d);
2553 assert!(a == c * b + d);
2558 fn test_div_mod_floor() {
2559 fn check_sub(a: &BigInt, b: &BigInt, ans_d: &BigInt, ans_m: &BigInt) {
2560 let (d, m) = a.div_mod_floor(b);
2562 assert_eq!(m.sign, b.sign);
2564 assert!(m.abs() <= b.abs());
2565 assert!(*a == b * d + m);
2566 assert!(d == *ans_d);
2567 assert!(m == *ans_m);
2570 fn check(a: &BigInt, b: &BigInt, d: &BigInt, m: &BigInt) {
2572 check_sub(a, b, d, m);
2573 check_sub(a, &b.neg(), &d.neg(), m);
2574 check_sub(&a.neg(), b, &d.neg(), m);
2575 check_sub(&a.neg(), &b.neg(), d, m);
2577 check_sub(a, b, d, m);
2578 check_sub(a, &b.neg(), &(d.neg() - One::one()), &(m - *b));
2579 check_sub(&a.neg(), b, &(d.neg() - One::one()), &(b - *m));
2580 check_sub(&a.neg(), &b.neg(), d, &m.neg());
2584 for elm in mul_triples.iter() {
2585 let (a_vec, b_vec, c_vec) = *elm;
2586 let a = BigInt::from_slice(Plus, a_vec);
2587 let b = BigInt::from_slice(Plus, b_vec);
2588 let c = BigInt::from_slice(Plus, c_vec);
2590 if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); }
2591 if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); }
2594 for elm in div_rem_quadruples.iter() {
2595 let (a_vec, b_vec, c_vec, d_vec) = *elm;
2596 let a = BigInt::from_slice(Plus, a_vec);
2597 let b = BigInt::from_slice(Plus, b_vec);
2598 let c = BigInt::from_slice(Plus, c_vec);
2599 let d = BigInt::from_slice(Plus, d_vec);
2602 check(&a, &b, &c, &d);
2610 fn check_sub(a: &BigInt, b: &BigInt, ans_q: &BigInt, ans_r: &BigInt) {
2611 let (q, r) = a.div_rem(b);
2613 assert_eq!(r.sign, a.sign);
2615 assert!(r.abs() <= b.abs());
2616 assert!(*a == b * q + r);
2617 assert!(q == *ans_q);
2618 assert!(r == *ans_r);
2621 fn check(a: &BigInt, b: &BigInt, q: &BigInt, r: &BigInt) {
2622 check_sub(a, b, q, r);
2623 check_sub(a, &b.neg(), &q.neg(), r);
2624 check_sub(&a.neg(), b, &q.neg(), &r.neg());
2625 check_sub(&a.neg(), &b.neg(), q, &r.neg());
2627 for elm in mul_triples.iter() {
2628 let (a_vec, b_vec, c_vec) = *elm;
2629 let a = BigInt::from_slice(Plus, a_vec);
2630 let b = BigInt::from_slice(Plus, b_vec);
2631 let c = BigInt::from_slice(Plus, c_vec);
2633 if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); }
2634 if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); }
2637 for elm in div_rem_quadruples.iter() {
2638 let (a_vec, b_vec, c_vec, d_vec) = *elm;
2639 let a = BigInt::from_slice(Plus, a_vec);
2640 let b = BigInt::from_slice(Plus, b_vec);
2641 let c = BigInt::from_slice(Plus, c_vec);
2642 let d = BigInt::from_slice(Plus, d_vec);
2645 check(&a, &b, &c, &d);
2651 fn test_checked_add() {
2652 for elm in sum_triples.iter() {
2653 let (aVec, bVec, cVec) = *elm;
2654 let a = BigInt::from_slice(Plus, aVec);
2655 let b = BigInt::from_slice(Plus, bVec);
2656 let c = BigInt::from_slice(Plus, cVec);
2658 assert!(a.checked_add(&b).unwrap() == c);
2659 assert!(b.checked_add(&a).unwrap() == c);
2660 assert!(c.checked_add(&(-a)).unwrap() == b);
2661 assert!(c.checked_add(&(-b)).unwrap() == a);
2662 assert!(a.checked_add(&(-c)).unwrap() == (-b));
2663 assert!(b.checked_add(&(-c)).unwrap() == (-a));
2664 assert!((-a).checked_add(&(-b)).unwrap() == (-c))
2665 assert!(a.checked_add(&(-a)).unwrap() == Zero::zero());
2670 fn test_checked_sub() {
2671 for elm in sum_triples.iter() {
2672 let (aVec, bVec, cVec) = *elm;
2673 let a = BigInt::from_slice(Plus, aVec);
2674 let b = BigInt::from_slice(Plus, bVec);
2675 let c = BigInt::from_slice(Plus, cVec);
2677 assert!(c.checked_sub(&a).unwrap() == b);
2678 assert!(c.checked_sub(&b).unwrap() == a);
2679 assert!((-b).checked_sub(&a).unwrap() == (-c))
2680 assert!((-a).checked_sub(&b).unwrap() == (-c))
2681 assert!(b.checked_sub(&(-a)).unwrap() == c);
2682 assert!(a.checked_sub(&(-b)).unwrap() == c);
2683 assert!((-c).checked_sub(&(-a)).unwrap() == (-b));
2684 assert!(a.checked_sub(&a).unwrap() == Zero::zero());
2689 fn test_checked_mul() {
2690 for elm in mul_triples.iter() {
2691 let (aVec, bVec, cVec) = *elm;
2692 let a = BigInt::from_slice(Plus, aVec);
2693 let b = BigInt::from_slice(Plus, bVec);
2694 let c = BigInt::from_slice(Plus, cVec);
2696 assert!(a.checked_mul(&b).unwrap() == c);
2697 assert!(b.checked_mul(&a).unwrap() == c);
2699 assert!((-a).checked_mul(&b).unwrap() == -c);
2700 assert!((-b).checked_mul(&a).unwrap() == -c);
2703 for elm in div_rem_quadruples.iter() {
2704 let (aVec, bVec, cVec, dVec) = *elm;
2705 let a = BigInt::from_slice(Plus, aVec);
2706 let b = BigInt::from_slice(Plus, bVec);
2707 let c = BigInt::from_slice(Plus, cVec);
2708 let d = BigInt::from_slice(Plus, dVec);
2710 assert!(a == b.checked_mul(&c).unwrap() + d);
2711 assert!(a == c.checked_mul(&b).unwrap() + d);
2715 fn test_checked_div() {
2716 for elm in mul_triples.iter() {
2717 let (aVec, bVec, cVec) = *elm;
2718 let a = BigInt::from_slice(Plus, aVec);
2719 let b = BigInt::from_slice(Plus, bVec);
2720 let c = BigInt::from_slice(Plus, cVec);
2723 assert!(c.checked_div(&a).unwrap() == b);
2724 assert!((-c).checked_div(&(-a)).unwrap() == b);
2725 assert!((-c).checked_div(&a).unwrap() == -b);
2728 assert!(c.checked_div(&b).unwrap() == a);
2729 assert!((-c).checked_div(&(-b)).unwrap() == a);
2730 assert!((-c).checked_div(&b).unwrap() == -a);
2733 assert!(c.checked_div(&Zero::zero()).is_none());
2734 assert!((-c).checked_div(&Zero::zero()).is_none());
2740 fn check(a: int, b: int, c: int) {
2741 let big_a: BigInt = FromPrimitive::from_int(a).unwrap();
2742 let big_b: BigInt = FromPrimitive::from_int(b).unwrap();
2743 let big_c: BigInt = FromPrimitive::from_int(c).unwrap();
2745 assert_eq!(big_a.gcd(&big_b), big_c);
2760 fn check(a: int, b: int, c: int) {
2761 let big_a: BigInt = FromPrimitive::from_int(a).unwrap();
2762 let big_b: BigInt = FromPrimitive::from_int(b).unwrap();
2763 let big_c: BigInt = FromPrimitive::from_int(c).unwrap();
2765 assert_eq!(big_a.lcm(&big_b), big_c);
2780 let zero: BigInt = Zero::zero();
2781 let one: BigInt = One::one();
2782 assert_eq!((-one).abs_sub(&one), zero);
2783 let one: BigInt = One::one();
2784 let zero: BigInt = Zero::zero();
2785 assert_eq!(one.abs_sub(&one), zero);
2786 let one: BigInt = One::one();
2787 let zero: BigInt = Zero::zero();
2788 assert_eq!(one.abs_sub(&zero), one);
2789 let one: BigInt = One::one();
2790 let two: BigInt = FromPrimitive::from_int(2).unwrap();
2791 assert_eq!(one.abs_sub(&-one), two);
2795 fn test_to_str_radix() {
2796 fn check(n: int, ans: &str) {
2797 let n: BigInt = FromPrimitive::from_int(n).unwrap();
2798 assert!(ans == n.to_str_radix(10).as_slice());
2809 fn test_from_str_radix() {
2810 fn check(s: &str, ans: Option<int>) {
2811 let ans = ans.map(|n| {
2812 let x: BigInt = FromPrimitive::from_int(n).unwrap();
2815 assert_eq!(FromStrRadix::from_str_radix(s, 10), ans);
2817 check("10", Some(10));
2818 check("1", Some(1));
2819 check("0", Some(0));
2820 check("-1", Some(-1));
2821 check("-10", Some(-10));
2825 // issue 10522, this hit an edge case that caused it to
2826 // attempt to allocate a vector of size (-1u) == huge.
2828 from_str(format!("1{}", "0".repeat(36)).as_slice()).unwrap();
2829 let _y = x.to_string();
2834 assert!(-BigInt::new(Plus, vec!(1, 1, 1)) ==
2835 BigInt::new(Minus, vec!(1, 1, 1)));
2836 assert!(-BigInt::new(Minus, vec!(1, 1, 1)) ==
2837 BigInt::new(Plus, vec!(1, 1, 1)));
2838 let zero: BigInt = Zero::zero();
2839 assert_eq!(-zero, zero);
2844 let mut rng = task_rng();
2845 let _n: BigInt = rng.gen_bigint(137);
2846 assert!(rng.gen_bigint(0).is_zero());
2850 fn test_rand_range() {
2851 let mut rng = task_rng();
2853 for _ in range(0u, 10) {
2854 assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_uint(236).unwrap(),
2855 &FromPrimitive::from_uint(237).unwrap()),
2856 FromPrimitive::from_uint(236).unwrap());
2859 fn check(l: BigInt, u: BigInt) {
2860 let mut rng = task_rng();
2861 for _ in range(0u, 1000) {
2862 let n: BigInt = rng.gen_bigint_range(&l, &u);
2867 let l: BigInt = FromPrimitive::from_uint(403469000 + 2352).unwrap();
2868 let u: BigInt = FromPrimitive::from_uint(403469000 + 3513).unwrap();
2869 check( l.clone(), u.clone());
2870 check(-l.clone(), u.clone());
2871 check(-u.clone(), -l.clone());
2876 fn test_zero_rand_range() {
2877 task_rng().gen_bigint_range(&FromPrimitive::from_int(54).unwrap(),
2878 &FromPrimitive::from_int(54).unwrap());
2883 fn test_negative_rand_range() {
2884 let mut rng = task_rng();
2885 let l = FromPrimitive::from_uint(2352).unwrap();
2886 let u = FromPrimitive::from_uint(3513).unwrap();
2887 // Switching u and l should fail:
2888 let _n: BigInt = rng.gen_bigint_range(&u, &l);
2895 use self::test::Bencher;
2898 use std::mem::replace;
2899 use std::num::{FromPrimitive, Zero, One};
2901 fn factorial(n: uint) -> BigUint {
2902 let mut f: BigUint = One::one();
2903 for i in iter::range_inclusive(1, n) {
2904 f = f * FromPrimitive::from_uint(i).unwrap();
2909 fn fib(n: uint) -> BigUint {
2910 let mut f0: BigUint = Zero::zero();
2911 let mut f1: BigUint = One::one();
2912 for _ in range(0, n) {
2914 f0 = replace(&mut f1, f2);
2920 fn factorial_100(b: &mut Bencher) {
2927 fn fib_100(b: &mut Bencher) {
2934 fn to_string(b: &mut Bencher) {
2935 let fac = factorial(100);
2946 fn shr(b: &mut Bencher) {
2947 let n = { let one : BigUint = One::one(); one << 1000 };
2949 let mut m = n.clone();
2950 for _ in range(0u, 10) {