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);
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 fmt::Show for BigUint {
154 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
155 write!(f, "{}", self.to_str_radix(10))
159 impl FromStr for BigUint {
161 fn from_str(s: &str) -> Option<BigUint> {
162 FromStrRadix::from_str_radix(s, 10)
166 impl Num for BigUint {}
168 impl BitAnd<BigUint, BigUint> for BigUint {
169 fn bitand(&self, other: &BigUint) -> BigUint {
170 BigUint::new(self.data.iter().zip(other.data.iter()).map(|(ai, bi)| *ai & *bi).collect())
174 impl BitOr<BigUint, BigUint> for BigUint {
175 fn bitor(&self, other: &BigUint) -> BigUint {
176 let zeros = ZERO_VEC.iter().cycle();
177 let (a, b) = if self.data.len() > other.data.len() { (self, other) } else { (other, self) };
178 let ored = a.data.iter().zip(b.data.iter().chain(zeros)).map(
181 return BigUint::new(ored);
185 impl BitXor<BigUint, BigUint> for BigUint {
186 fn bitxor(&self, other: &BigUint) -> BigUint {
187 let zeros = ZERO_VEC.iter().cycle();
188 let (a, b) = if self.data.len() > other.data.len() { (self, other) } else { (other, self) };
189 let xored = a.data.iter().zip(b.data.iter().chain(zeros)).map(
192 return BigUint::new(xored);
196 impl Shl<uint, BigUint> for BigUint {
198 fn shl(&self, rhs: &uint) -> BigUint {
199 let n_unit = *rhs / BigDigit::bits;
200 let n_bits = *rhs % BigDigit::bits;
201 return self.shl_unit(n_unit).shl_bits(n_bits);
205 impl Shr<uint, BigUint> for BigUint {
207 fn shr(&self, rhs: &uint) -> BigUint {
208 let n_unit = *rhs / BigDigit::bits;
209 let n_bits = *rhs % BigDigit::bits;
210 return self.shr_unit(n_unit).shr_bits(n_bits);
214 impl Zero for BigUint {
216 fn zero() -> BigUint { BigUint::new(Vec::new()) }
219 fn is_zero(&self) -> bool { self.data.is_empty() }
222 impl One for BigUint {
224 fn one() -> BigUint { BigUint::new(vec!(1)) }
227 impl Unsigned for BigUint {}
229 impl Add<BigUint, BigUint> for BigUint {
230 fn add(&self, other: &BigUint) -> BigUint {
231 let zeros = ZERO_VEC.iter().cycle();
232 let (a, b) = if self.data.len() > other.data.len() { (self, other) } else { (other, self) };
235 let mut sum: Vec<BigDigit> = a.data.iter().zip(b.data.iter().chain(zeros)).map(|(ai, bi)| {
236 let (hi, lo) = BigDigit::from_doublebigdigit(
237 (*ai as DoubleBigDigit) + (*bi as DoubleBigDigit) + (carry as DoubleBigDigit));
241 if carry != 0 { sum.push(carry); }
242 return BigUint::new(sum);
246 impl Sub<BigUint, BigUint> for BigUint {
247 fn sub(&self, other: &BigUint) -> BigUint {
248 let new_len = cmp::max(self.data.len(), other.data.len());
249 let zeros = ZERO_VEC.iter().cycle();
250 let (a, b) = (self.data.iter().chain(zeros.clone()), other.data.iter().chain(zeros));
253 let diff: Vec<BigDigit> = a.take(new_len).zip(b).map(|(ai, bi)| {
254 let (hi, lo) = BigDigit::from_doublebigdigit(
256 + (*ai as DoubleBigDigit)
257 - (*bi as DoubleBigDigit)
258 - (borrow as DoubleBigDigit)
261 hi * (base) + lo == 1*(base) + ai - bi - borrow
262 => ai - bi - borrow < 0 <=> hi == 0
264 borrow = if hi == 0 { 1 } else { 0 };
269 "Cannot subtract other from self because other is larger than self.");
270 return BigUint::new(diff);
274 impl Mul<BigUint, BigUint> for BigUint {
275 fn mul(&self, other: &BigUint) -> BigUint {
276 if self.is_zero() || other.is_zero() { return Zero::zero(); }
278 let (s_len, o_len) = (self.data.len(), other.data.len());
279 if s_len == 1 { return mul_digit(other, self.data.as_slice()[0]); }
280 if o_len == 1 { return mul_digit(self, other.data.as_slice()[0]); }
282 // Using Karatsuba multiplication
283 // (a1 * base + a0) * (b1 * base + b0)
284 // = a1*b1 * base^2 +
285 // (a1*b1 + a0*b0 - (a1-b0)*(b1-a0)) * base +
287 let half_len = cmp::max(s_len, o_len) / 2;
288 let (s_hi, s_lo) = cut_at(self, half_len);
289 let (o_hi, o_lo) = cut_at(other, half_len);
291 let ll = s_lo * o_lo;
292 let hh = s_hi * o_hi;
294 let (s1, n1) = sub_sign(s_hi, s_lo);
295 let (s2, n2) = sub_sign(o_hi, o_lo);
297 (Equal, _) | (_, Equal) => hh + ll,
298 (Less, Greater) | (Greater, Less) => hh + ll + (n1 * n2),
299 (Less, Less) | (Greater, Greater) => hh + ll - (n1 * n2)
303 return ll + mm.shl_unit(half_len) + hh.shl_unit(half_len * 2);
306 fn mul_digit(a: &BigUint, n: BigDigit) -> BigUint {
307 if n == 0 { return Zero::zero(); }
308 if n == 1 { return (*a).clone(); }
311 let mut prod: Vec<BigDigit> = a.data.iter().map(|ai| {
312 let (hi, lo) = BigDigit::from_doublebigdigit(
313 (*ai as DoubleBigDigit) * (n as DoubleBigDigit) + (carry as DoubleBigDigit)
318 if carry != 0 { prod.push(carry); }
319 return BigUint::new(prod);
323 fn cut_at(a: &BigUint, n: uint) -> (BigUint, BigUint) {
324 let mid = cmp::min(a.data.len(), n);
325 return (BigUint::from_slice(a.data.slice(mid, a.data.len())),
326 BigUint::from_slice(a.data.slice(0, mid)));
330 fn sub_sign(a: BigUint, b: BigUint) -> (Ordering, BigUint) {
332 Less => (Less, b - a),
333 Greater => (Greater, a - b),
334 _ => (Equal, Zero::zero())
340 impl Div<BigUint, BigUint> for BigUint {
342 fn div(&self, other: &BigUint) -> BigUint {
343 let (q, _) = self.div_rem(other);
348 impl Rem<BigUint, BigUint> for BigUint {
350 fn rem(&self, other: &BigUint) -> BigUint {
351 let (_, r) = self.div_rem(other);
356 impl Neg<BigUint> for BigUint {
358 fn neg(&self) -> BigUint { fail!() }
361 impl CheckedAdd for BigUint {
363 fn checked_add(&self, v: &BigUint) -> Option<BigUint> {
364 return Some(self.add(v));
368 impl CheckedSub for BigUint {
370 fn checked_sub(&self, v: &BigUint) -> Option<BigUint> {
374 return Some(self.sub(v));
378 impl CheckedMul for BigUint {
380 fn checked_mul(&self, v: &BigUint) -> Option<BigUint> {
381 return Some(self.mul(v));
385 impl CheckedDiv for BigUint {
387 fn checked_div(&self, v: &BigUint) -> Option<BigUint> {
391 return Some(self.div(v));
395 impl Integer for BigUint {
397 fn div_rem(&self, other: &BigUint) -> (BigUint, BigUint) {
398 self.div_mod_floor(other)
402 fn div_floor(&self, other: &BigUint) -> BigUint {
403 let (d, _) = self.div_mod_floor(other);
408 fn mod_floor(&self, other: &BigUint) -> BigUint {
409 let (_, m) = self.div_mod_floor(other);
413 fn div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint) {
414 if other.is_zero() { fail!() }
415 if self.is_zero() { return (Zero::zero(), Zero::zero()); }
416 if *other == One::one() { return ((*self).clone(), Zero::zero()); }
418 match self.cmp(other) {
419 Less => return (Zero::zero(), (*self).clone()),
420 Equal => return (One::one(), Zero::zero()),
421 Greater => {} // Do nothing
425 let mut n = *other.data.last().unwrap();
426 while n < (1 << BigDigit::bits - 2) {
430 assert!(shift < BigDigit::bits);
431 let (d, m) = div_mod_floor_inner(self << shift, other << shift);
432 return (d, m >> shift);
435 fn div_mod_floor_inner(a: BigUint, b: BigUint) -> (BigUint, BigUint) {
437 let mut d: BigUint = Zero::zero();
440 let (d0, d_unit, b_unit) = div_estimate(&m, &b, n);
442 let mut prod = b * d0;
444 // FIXME(#5992): assignment operator overloads
447 // FIXME(#5992): assignment operator overloads
456 // FIXME(#5992): assignment operator overloads
459 // FIXME(#5992): assignment operator overloads
467 fn div_estimate(a: &BigUint, b: &BigUint, n: uint)
468 -> (BigUint, BigUint, BigUint) {
469 if a.data.len() < n {
470 return (Zero::zero(), Zero::zero(), (*a).clone());
473 let an = a.data.tailn(a.data.len() - n);
474 let bn = *b.data.last().unwrap();
475 let mut d = Vec::with_capacity(an.len());
477 for elt in an.iter().rev() {
478 let ai = BigDigit::to_doublebigdigit(carry, *elt);
479 let di = ai / (bn as DoubleBigDigit);
480 assert!(di < BigDigit::base);
481 carry = (ai % (bn as DoubleBigDigit)) as BigDigit;
482 d.push(di as BigDigit)
486 let shift = (a.data.len() - an.len()) - (b.data.len() - 1);
488 return (BigUint::new(d), One::one(), (*b).clone());
490 let one: BigUint = One::one();
491 return (BigUint::new(d).shl_unit(shift),
497 /// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
499 /// The result is always positive.
501 fn gcd(&self, other: &BigUint) -> BigUint {
502 // Use Euclid's algorithm
503 let mut m = (*self).clone();
504 let mut n = (*other).clone();
513 /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
515 fn lcm(&self, other: &BigUint) -> BigUint { ((*self * *other) / self.gcd(other)) }
517 /// Deprecated, use `is_multiple_of` instead.
518 #[deprecated = "function renamed to `is_multiple_of`"]
520 fn divides(&self, other: &BigUint) -> bool { return self.is_multiple_of(other); }
522 /// Returns `true` if the number is a multiple of `other`.
524 fn is_multiple_of(&self, other: &BigUint) -> bool { (*self % *other).is_zero() }
526 /// Returns `true` if the number is divisible by `2`.
528 fn is_even(&self) -> bool {
529 // Considering only the last digit.
530 match self.data.as_slice().head() {
531 Some(x) => x.is_even(),
536 /// Returns `true` if the number is not divisible by `2`.
538 fn is_odd(&self) -> bool { !self.is_even() }
541 impl ToPrimitive for BigUint {
543 fn to_i64(&self) -> Option<i64> {
544 self.to_u64().and_then(|n| {
545 // If top bit of u64 is set, it's too large to convert to i64.
554 // `DoubleBigDigit` size dependent
556 fn to_u64(&self) -> Option<u64> {
557 match self.data.len() {
559 1 => Some(self.data.as_slice()[0] as u64),
560 2 => Some(BigDigit::to_doublebigdigit(self.data.as_slice()[1], self.data.as_slice()[0])
567 impl FromPrimitive for BigUint {
569 fn from_i64(n: i64) -> Option<BigUint> {
571 FromPrimitive::from_u64(n as u64)
579 // `DoubleBigDigit` size dependent
581 fn from_u64(n: u64) -> Option<BigUint> {
582 let n = match BigDigit::from_doublebigdigit(n) {
583 (0, 0) => Zero::zero(),
584 (0, n0) => BigUint::new(vec!(n0)),
585 (n1, n0) => BigUint::new(vec!(n0, n1))
591 /// A generic trait for converting a value to a `BigUint`.
592 pub trait ToBigUint {
593 /// Converts the value of `self` to a `BigUint`.
594 fn to_biguint(&self) -> Option<BigUint>;
597 impl ToBigUint for BigInt {
599 fn to_biguint(&self) -> Option<BigUint> {
600 if self.sign == Plus {
601 Some(self.data.clone())
602 } else if self.sign == Zero {
610 impl ToBigUint for BigUint {
612 fn to_biguint(&self) -> Option<BigUint> {
617 macro_rules! impl_to_biguint(
618 ($T:ty, $from_ty:path) => {
619 impl ToBigUint for $T {
621 fn to_biguint(&self) -> Option<BigUint> {
628 impl_to_biguint!(int, FromPrimitive::from_int)
629 impl_to_biguint!(i8, FromPrimitive::from_i8)
630 impl_to_biguint!(i16, FromPrimitive::from_i16)
631 impl_to_biguint!(i32, FromPrimitive::from_i32)
632 impl_to_biguint!(i64, FromPrimitive::from_i64)
633 impl_to_biguint!(uint, FromPrimitive::from_uint)
634 impl_to_biguint!(u8, FromPrimitive::from_u8)
635 impl_to_biguint!(u16, FromPrimitive::from_u16)
636 impl_to_biguint!(u32, FromPrimitive::from_u32)
637 impl_to_biguint!(u64, FromPrimitive::from_u64)
639 impl ToStrRadix for BigUint {
640 fn to_str_radix(&self, radix: uint) -> String {
641 assert!(1 < radix && radix <= 16, "The radix must be within (1, 16]");
642 let (base, max_len) = get_radix_base(radix);
643 if base == BigDigit::base {
644 return fill_concat(self.data.as_slice(), radix, max_len)
646 return fill_concat(convert_base(self, base).as_slice(), radix, max_len);
648 fn convert_base(n: &BigUint, base: DoubleBigDigit) -> Vec<BigDigit> {
649 let divider = base.to_biguint().unwrap();
650 let mut result = Vec::new();
651 let mut m = n.clone();
653 let (d, m0) = m.div_mod_floor(÷r);
654 result.push(m0.to_uint().unwrap() as BigDigit);
658 result.push(m.to_uint().unwrap() as BigDigit);
663 fn fill_concat(v: &[BigDigit], radix: uint, l: uint) -> String {
665 return "0".to_string()
667 let mut s = String::with_capacity(v.len() * l);
668 for n in v.iter().rev() {
669 let ss = (*n as uint).to_str_radix(radix);
670 s.push_str("0".repeat(l - ss.len()).as_slice());
671 s.push_str(ss.as_slice());
673 s.as_slice().trim_left_chars('0').to_string()
678 impl FromStrRadix for BigUint {
679 /// Creates and initializes a `BigUint`.
681 fn from_str_radix(s: &str, radix: uint) -> Option<BigUint> {
682 BigUint::parse_bytes(s.as_bytes(), radix)
687 /// Creates and initializes a `BigUint`.
689 /// The digits are be in base 2^32.
691 pub fn new(mut digits: Vec<BigDigit>) -> BigUint {
692 // omit trailing zeros
693 let new_len = digits.iter().rposition(|n| *n != 0).map_or(0, |p| p + 1);
694 digits.truncate(new_len);
695 BigUint { data: digits }
698 /// Creates and initializes a `BigUint`.
700 /// The digits are be in base 2^32.
702 pub fn from_slice(slice: &[BigDigit]) -> BigUint {
703 BigUint::new(Vec::from_slice(slice))
706 /// Creates and initializes a `BigUint`.
707 pub fn parse_bytes(buf: &[u8], radix: uint) -> Option<BigUint> {
708 let (base, unit_len) = get_radix_base(radix);
709 let base_num = match base.to_biguint() {
710 Some(base_num) => base_num,
711 None => { return None; }
714 let mut end = buf.len();
715 let mut n: BigUint = Zero::zero();
716 let mut power: BigUint = One::one();
718 let start = cmp::max(end, unit_len) - unit_len;
719 match uint::parse_bytes(buf.slice(start, end), radix) {
721 let d: Option<BigUint> = FromPrimitive::from_uint(d);
724 // FIXME(#5992): assignment operator overloads
728 None => { return None; }
731 None => { return None; }
737 // FIXME(#5992): assignment operator overloads
738 // power *= base_num;
739 power = power * base_num;
744 fn shl_unit(&self, n_unit: uint) -> BigUint {
745 if n_unit == 0 || self.is_zero() { return (*self).clone(); }
747 BigUint::new(Vec::from_elem(n_unit, ZERO_BIG_DIGIT).append(self.data.as_slice()))
751 fn shl_bits(&self, n_bits: uint) -> BigUint {
752 if n_bits == 0 || self.is_zero() { return (*self).clone(); }
755 let mut shifted: Vec<BigDigit> = self.data.iter().map(|elem| {
756 let (hi, lo) = BigDigit::from_doublebigdigit(
757 (*elem as DoubleBigDigit) << n_bits | (carry as DoubleBigDigit)
762 if carry != 0 { shifted.push(carry); }
763 return BigUint::new(shifted);
767 fn shr_unit(&self, n_unit: uint) -> BigUint {
768 if n_unit == 0 { return (*self).clone(); }
769 if self.data.len() < n_unit { return Zero::zero(); }
770 return BigUint::from_slice(
771 self.data.slice(n_unit, self.data.len())
776 fn shr_bits(&self, n_bits: uint) -> BigUint {
777 if n_bits == 0 || self.data.is_empty() { return (*self).clone(); }
780 let mut shifted_rev = Vec::with_capacity(self.data.len());
781 for elem in self.data.iter().rev() {
782 shifted_rev.push((*elem >> n_bits) | borrow);
783 borrow = *elem << (BigDigit::bits - n_bits);
785 let shifted = { shifted_rev.reverse(); shifted_rev };
786 return BigUint::new(shifted);
789 /// Determines the fewest bits necessary to express the `BigUint`.
790 pub fn bits(&self) -> uint {
791 if self.is_zero() { return 0; }
792 let zeros = self.data.last().unwrap().leading_zeros();
793 return self.data.len()*BigDigit::bits - (zeros as uint);
797 // `DoubleBigDigit` size dependent
799 fn get_radix_base(radix: uint) -> (DoubleBigDigit, uint) {
801 2 => (4294967296, 32),
802 3 => (3486784401, 20),
803 4 => (4294967296, 16),
804 5 => (1220703125, 13),
805 6 => (2176782336, 12),
806 7 => (1977326743, 11),
807 8 => (1073741824, 10),
808 9 => (3486784401, 10),
809 10 => (1000000000, 9),
810 11 => (2357947691, 9),
811 12 => (429981696, 8),
812 13 => (815730721, 8),
813 14 => (1475789056, 8),
814 15 => (2562890625, 8),
815 16 => (4294967296, 8),
816 _ => fail!("The radix must be within (1, 16]")
820 /// A Sign is a `BigInt`'s composing element.
821 #[deriving(PartialEq, PartialOrd, Eq, Ord, Clone, Show)]
822 pub enum Sign { Minus, Zero, Plus }
824 impl Neg<Sign> for Sign {
825 /// Negate Sign value.
827 fn neg(&self) -> Sign {
836 /// A big signed integer type.
843 impl PartialEq for BigInt {
845 fn eq(&self, other: &BigInt) -> bool {
846 self.cmp(other) == Equal
850 impl Eq for BigInt {}
852 impl PartialOrd for BigInt {
854 fn partial_cmp(&self, other: &BigInt) -> Option<Ordering> {
855 Some(self.cmp(other))
859 impl Ord for BigInt {
861 fn cmp(&self, other: &BigInt) -> Ordering {
862 let scmp = self.sign.cmp(&other.sign);
863 if scmp != Equal { return scmp; }
867 Plus => self.data.cmp(&other.data),
868 Minus => other.data.cmp(&self.data),
873 impl Default for BigInt {
875 fn default() -> BigInt { Zero::zero() }
878 impl fmt::Show for BigInt {
879 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
880 write!(f, "{}", self.to_str_radix(10))
884 impl FromStr for BigInt {
886 fn from_str(s: &str) -> Option<BigInt> {
887 FromStrRadix::from_str_radix(s, 10)
891 impl Num for BigInt {}
893 impl Shl<uint, BigInt> for BigInt {
895 fn shl(&self, rhs: &uint) -> BigInt {
896 BigInt::from_biguint(self.sign, self.data << *rhs)
900 impl Shr<uint, BigInt> for BigInt {
902 fn shr(&self, rhs: &uint) -> BigInt {
903 BigInt::from_biguint(self.sign, self.data >> *rhs)
907 impl Zero for BigInt {
909 fn zero() -> BigInt {
910 BigInt::from_biguint(Zero, Zero::zero())
914 fn is_zero(&self) -> bool { self.sign == Zero }
917 impl One for BigInt {
920 BigInt::from_biguint(Plus, One::one())
924 impl Signed for BigInt {
926 fn abs(&self) -> BigInt {
928 Plus | Zero => self.clone(),
929 Minus => BigInt::from_biguint(Plus, self.data.clone())
934 fn abs_sub(&self, other: &BigInt) -> BigInt {
935 if *self <= *other { Zero::zero() } else { *self - *other }
939 fn signum(&self) -> BigInt {
941 Plus => BigInt::from_biguint(Plus, One::one()),
942 Minus => BigInt::from_biguint(Minus, One::one()),
943 Zero => Zero::zero(),
948 fn is_positive(&self) -> bool { self.sign == Plus }
951 fn is_negative(&self) -> bool { self.sign == Minus }
954 impl Add<BigInt, BigInt> for BigInt {
956 fn add(&self, other: &BigInt) -> BigInt {
957 match (self.sign, other.sign) {
958 (Zero, _) => other.clone(),
959 (_, Zero) => self.clone(),
960 (Plus, Plus) => BigInt::from_biguint(Plus, self.data + other.data),
961 (Plus, Minus) => self - (-*other),
962 (Minus, Plus) => other - (-*self),
963 (Minus, Minus) => -((-self) + (-*other))
968 impl Sub<BigInt, BigInt> for BigInt {
970 fn sub(&self, other: &BigInt) -> BigInt {
971 match (self.sign, other.sign) {
973 (_, Zero) => self.clone(),
974 (Plus, Plus) => match self.data.cmp(&other.data) {
975 Less => BigInt::from_biguint(Minus, other.data - self.data),
976 Greater => BigInt::from_biguint(Plus, self.data - other.data),
977 Equal => Zero::zero()
979 (Plus, Minus) => self + (-*other),
980 (Minus, Plus) => -((-self) + *other),
981 (Minus, Minus) => (-other) - (-*self)
986 impl Mul<BigInt, BigInt> for BigInt {
988 fn mul(&self, other: &BigInt) -> BigInt {
989 match (self.sign, other.sign) {
990 (Zero, _) | (_, Zero) => Zero::zero(),
991 (Plus, Plus) | (Minus, Minus) => {
992 BigInt::from_biguint(Plus, self.data * other.data)
994 (Plus, Minus) | (Minus, Plus) => {
995 BigInt::from_biguint(Minus, self.data * other.data)
1001 impl Div<BigInt, BigInt> for BigInt {
1003 fn div(&self, other: &BigInt) -> BigInt {
1004 let (q, _) = self.div_rem(other);
1009 impl Rem<BigInt, BigInt> for BigInt {
1011 fn rem(&self, other: &BigInt) -> BigInt {
1012 let (_, r) = self.div_rem(other);
1017 impl Neg<BigInt> for BigInt {
1019 fn neg(&self) -> BigInt {
1020 BigInt::from_biguint(self.sign.neg(), self.data.clone())
1024 impl CheckedAdd for BigInt {
1026 fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
1027 return Some(self.add(v));
1031 impl CheckedSub for BigInt {
1033 fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
1034 return Some(self.sub(v));
1038 impl CheckedMul for BigInt {
1040 fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
1041 return Some(self.mul(v));
1045 impl CheckedDiv for BigInt {
1047 fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
1051 return Some(self.div(v));
1056 impl Integer for BigInt {
1058 fn div_rem(&self, other: &BigInt) -> (BigInt, BigInt) {
1059 // r.sign == self.sign
1060 let (d_ui, r_ui) = self.data.div_mod_floor(&other.data);
1061 let d = BigInt::from_biguint(Plus, d_ui);
1062 let r = BigInt::from_biguint(Plus, r_ui);
1063 match (self.sign, other.sign) {
1064 (_, Zero) => fail!(),
1065 (Plus, Plus) | (Zero, Plus) => ( d, r),
1066 (Plus, Minus) | (Zero, Minus) => (-d, r),
1067 (Minus, Plus) => (-d, -r),
1068 (Minus, Minus) => ( d, -r)
1073 fn div_floor(&self, other: &BigInt) -> BigInt {
1074 let (d, _) = self.div_mod_floor(other);
1079 fn mod_floor(&self, other: &BigInt) -> BigInt {
1080 let (_, m) = self.div_mod_floor(other);
1084 fn div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt) {
1085 // m.sign == other.sign
1086 let (d_ui, m_ui) = self.data.div_rem(&other.data);
1087 let d = BigInt::from_biguint(Plus, d_ui);
1088 let m = BigInt::from_biguint(Plus, m_ui);
1089 match (self.sign, other.sign) {
1090 (_, Zero) => fail!(),
1091 (Plus, Plus) | (Zero, Plus) => (d, m),
1092 (Plus, Minus) | (Zero, Minus) => if m.is_zero() {
1095 (-d - One::one(), m + *other)
1097 (Minus, Plus) => if m.is_zero() {
1100 (-d - One::one(), other - m)
1102 (Minus, Minus) => (d, -m)
1106 /// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
1108 /// The result is always positive.
1110 fn gcd(&self, other: &BigInt) -> BigInt {
1111 BigInt::from_biguint(Plus, self.data.gcd(&other.data))
1114 /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
1116 fn lcm(&self, other: &BigInt) -> BigInt {
1117 BigInt::from_biguint(Plus, self.data.lcm(&other.data))
1120 /// Deprecated, use `is_multiple_of` instead.
1121 #[deprecated = "function renamed to `is_multiple_of`"]
1123 fn divides(&self, other: &BigInt) -> bool { return self.is_multiple_of(other); }
1125 /// Returns `true` if the number is a multiple of `other`.
1127 fn is_multiple_of(&self, other: &BigInt) -> bool { self.data.is_multiple_of(&other.data) }
1129 /// Returns `true` if the number is divisible by `2`.
1131 fn is_even(&self) -> bool { self.data.is_even() }
1133 /// Returns `true` if the number is not divisible by `2`.
1135 fn is_odd(&self) -> bool { self.data.is_odd() }
1138 impl ToPrimitive for BigInt {
1140 fn to_i64(&self) -> Option<i64> {
1142 Plus => self.data.to_i64(),
1145 self.data.to_u64().and_then(|n| {
1146 let m: u64 = 1 << 63;
1160 fn to_u64(&self) -> Option<u64> {
1162 Plus => self.data.to_u64(),
1169 impl FromPrimitive for BigInt {
1171 fn from_i64(n: i64) -> Option<BigInt> {
1173 FromPrimitive::from_u64(n as u64).and_then(|n| {
1174 Some(BigInt::from_biguint(Plus, n))
1177 FromPrimitive::from_u64(u64::MAX - (n as u64) + 1).and_then(
1179 Some(BigInt::from_biguint(Minus, n))
1187 fn from_u64(n: u64) -> Option<BigInt> {
1191 FromPrimitive::from_u64(n).and_then(|n| {
1192 Some(BigInt::from_biguint(Plus, n))
1198 /// A generic trait for converting a value to a `BigInt`.
1199 pub trait ToBigInt {
1200 /// Converts the value of `self` to a `BigInt`.
1201 fn to_bigint(&self) -> Option<BigInt>;
1204 impl ToBigInt for BigInt {
1206 fn to_bigint(&self) -> Option<BigInt> {
1211 impl ToBigInt for BigUint {
1213 fn to_bigint(&self) -> Option<BigInt> {
1217 Some(BigInt { sign: Plus, data: self.clone() })
1222 macro_rules! impl_to_bigint(
1223 ($T:ty, $from_ty:path) => {
1224 impl ToBigInt for $T {
1226 fn to_bigint(&self) -> Option<BigInt> {
1233 impl_to_bigint!(int, FromPrimitive::from_int)
1234 impl_to_bigint!(i8, FromPrimitive::from_i8)
1235 impl_to_bigint!(i16, FromPrimitive::from_i16)
1236 impl_to_bigint!(i32, FromPrimitive::from_i32)
1237 impl_to_bigint!(i64, FromPrimitive::from_i64)
1238 impl_to_bigint!(uint, FromPrimitive::from_uint)
1239 impl_to_bigint!(u8, FromPrimitive::from_u8)
1240 impl_to_bigint!(u16, FromPrimitive::from_u16)
1241 impl_to_bigint!(u32, FromPrimitive::from_u32)
1242 impl_to_bigint!(u64, FromPrimitive::from_u64)
1244 impl ToStrRadix for BigInt {
1246 fn to_str_radix(&self, radix: uint) -> String {
1248 Plus => self.data.to_str_radix(radix),
1249 Zero => "0".to_string(),
1250 Minus => format!("-{}", self.data.to_str_radix(radix)),
1255 impl FromStrRadix for BigInt {
1256 /// Creates and initializes a BigInt.
1258 fn from_str_radix(s: &str, radix: uint) -> Option<BigInt> {
1259 BigInt::parse_bytes(s.as_bytes(), radix)
1263 pub trait RandBigInt {
1264 /// Generate a random `BigUint` of the given bit size.
1265 fn gen_biguint(&mut self, bit_size: uint) -> BigUint;
1267 /// Generate a random BigInt of the given bit size.
1268 fn gen_bigint(&mut self, bit_size: uint) -> BigInt;
1270 /// Generate a random `BigUint` less than the given bound. Fails
1271 /// when the bound is zero.
1272 fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint;
1274 /// Generate a random `BigUint` within the given range. The lower
1275 /// bound is inclusive; the upper bound is exclusive. Fails when
1276 /// the upper bound is not greater than the lower bound.
1277 fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint;
1279 /// Generate a random `BigInt` within the given range. The lower
1280 /// bound is inclusive; the upper bound is exclusive. Fails when
1281 /// the upper bound is not greater than the lower bound.
1282 fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt;
1285 impl<R: Rng> RandBigInt for R {
1286 fn gen_biguint(&mut self, bit_size: uint) -> BigUint {
1287 let (digits, rem) = bit_size.div_rem(&BigDigit::bits);
1288 let mut data = Vec::with_capacity(digits+1);
1289 for _ in range(0, digits) {
1290 data.push(self.gen());
1293 let final_digit: BigDigit = self.gen();
1294 data.push(final_digit >> (BigDigit::bits - rem));
1299 fn gen_bigint(&mut self, bit_size: uint) -> BigInt {
1300 // Generate a random BigUint...
1301 let biguint = self.gen_biguint(bit_size);
1302 // ...and then randomly assign it a Sign...
1303 let sign = if biguint.is_zero() {
1304 // ...except that if the BigUint is zero, we need to try
1305 // again with probability 0.5. This is because otherwise,
1306 // the probability of generating a zero BigInt would be
1307 // double that of any other number.
1309 return self.gen_bigint(bit_size);
1313 } else if self.gen() {
1318 BigInt::from_biguint(sign, biguint)
1321 fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint {
1322 assert!(!bound.is_zero());
1323 let bits = bound.bits();
1325 let n = self.gen_biguint(bits);
1326 if n < *bound { return n; }
1330 fn gen_biguint_range(&mut self,
1334 assert!(*lbound < *ubound);
1335 return *lbound + self.gen_biguint_below(&(*ubound - *lbound));
1338 fn gen_bigint_range(&mut self,
1342 assert!(*lbound < *ubound);
1343 let delta = (*ubound - *lbound).to_biguint().unwrap();
1344 return *lbound + self.gen_biguint_below(&delta).to_bigint().unwrap();
1349 /// Creates and initializes a BigInt.
1351 /// The digits are be in base 2^32.
1353 pub fn new(sign: Sign, digits: Vec<BigDigit>) -> BigInt {
1354 BigInt::from_biguint(sign, BigUint::new(digits))
1357 /// Creates and initializes a `BigInt`.
1359 /// The digits are be in base 2^32.
1361 pub fn from_biguint(sign: Sign, data: BigUint) -> BigInt {
1362 if sign == Zero || data.is_zero() {
1363 return BigInt { sign: Zero, data: Zero::zero() };
1365 BigInt { sign: sign, data: data }
1368 /// Creates and initializes a `BigInt`.
1370 pub fn from_slice(sign: Sign, slice: &[BigDigit]) -> BigInt {
1371 BigInt::from_biguint(sign, BigUint::from_slice(slice))
1374 /// Creates and initializes a `BigInt`.
1375 pub fn parse_bytes(buf: &[u8], radix: uint) -> Option<BigInt> {
1376 if buf.is_empty() { return None; }
1377 let mut sign = Plus;
1379 if buf[0] == ('-' as u8) {
1383 return BigUint::parse_bytes(buf.slice(start, buf.len()), radix)
1384 .map(|bu| BigInt::from_biguint(sign, bu));
1387 /// Converts this `BigInt` into a `BigUint`, if it's not negative.
1389 pub fn to_biguint(&self) -> Option<BigUint> {
1391 Plus => Some(self.data.clone()),
1392 Zero => Some(Zero::zero()),
1401 use super::{BigDigit, BigUint, ToBigUint};
1402 use super::{Plus, BigInt, RandBigInt, ToBigInt};
1404 use std::cmp::{Less, Equal, Greater};
1405 use std::from_str::FromStr;
1407 use std::num::{Zero, One, FromStrRadix, ToStrRadix};
1408 use std::num::{ToPrimitive, FromPrimitive};
1409 use std::num::CheckedDiv;
1410 use std::rand::task_rng;
1414 fn test_from_slice() {
1415 fn check(slice: &[BigDigit], data: &[BigDigit]) {
1416 assert!(data == BigUint::from_slice(slice).data.as_slice());
1419 check([0, 0, 0], []);
1420 check([1, 2, 0, 0], [1, 2]);
1421 check([0, 0, 1, 2], [0, 0, 1, 2]);
1422 check([0, 0, 1, 2, 0, 0], [0, 0, 1, 2]);
1428 let data: Vec<BigUint> = [ &[], &[1], &[2], &[-1], &[0, 1], &[2, 1], &[1, 1, 1] ]
1429 .iter().map(|v| BigUint::from_slice(*v)).collect();
1430 for (i, ni) in data.iter().enumerate() {
1431 for (j0, nj) in data.slice(i, data.len()).iter().enumerate() {
1434 assert_eq!(ni.cmp(nj), Equal);
1435 assert_eq!(nj.cmp(ni), Equal);
1437 assert!(!(ni != nj));
1440 assert!(!(ni < nj));
1441 assert!(!(ni > nj));
1443 assert_eq!(ni.cmp(nj), Less);
1444 assert_eq!(nj.cmp(ni), Greater);
1446 assert!(!(ni == nj));
1450 assert!(!(ni >= nj));
1452 assert!(!(ni > nj));
1454 assert!(!(nj <= ni));
1456 assert!(!(nj < ni));
1465 fn check(left: &[BigDigit],
1467 expected: &[BigDigit]) {
1468 assert_eq!(BigUint::from_slice(left) & BigUint::from_slice(right),
1469 BigUint::from_slice(expected));
1472 check([268, 482, 17],
1479 fn check(left: &[BigDigit],
1481 expected: &[BigDigit]) {
1482 assert_eq!(BigUint::from_slice(left) | BigUint::from_slice(right),
1483 BigUint::from_slice(expected));
1486 check([268, 482, 17],
1493 fn check(left: &[BigDigit],
1495 expected: &[BigDigit]) {
1496 assert_eq!(BigUint::from_slice(left) ^ BigUint::from_slice(right),
1497 BigUint::from_slice(expected));
1500 check([268, 482, 17],
1507 fn check(s: &str, shift: uint, ans: &str) {
1508 let opt_biguint: Option<BigUint> = FromStrRadix::from_str_radix(s, 16);
1509 let bu = (opt_biguint.unwrap() << shift).to_str_radix(16);
1510 assert_eq!(bu.as_slice(), ans);
1622 check("88887777666655554444333322221111", 16,
1623 "888877776666555544443333222211110000");
1628 fn check(s: &str, shift: uint, ans: &str) {
1629 let opt_biguint: Option<BigUint> =
1630 FromStrRadix::from_str_radix(s, 16);
1631 let bu = (opt_biguint.unwrap() >> shift).to_str_radix(16);
1632 assert_eq!(bu.as_slice(), ans);
1740 check("888877776666555544443333222211110000", 16,
1741 "88887777666655554444333322221111");
1744 // `DoubleBigDigit` size dependent
1746 fn test_convert_i64() {
1747 fn check(b1: BigUint, i: i64) {
1748 let b2: BigUint = FromPrimitive::from_i64(i).unwrap();
1750 assert!(b1.to_i64().unwrap() == i);
1753 check(Zero::zero(), 0);
1754 check(One::one(), 1);
1755 check(i64::MAX.to_biguint().unwrap(), i64::MAX);
1757 check(BigUint::new(vec!( )), 0);
1758 check(BigUint::new(vec!( 1 )), (1 << (0*BigDigit::bits)));
1759 check(BigUint::new(vec!(-1 )), (1 << (1*BigDigit::bits)) - 1);
1760 check(BigUint::new(vec!( 0, 1 )), (1 << (1*BigDigit::bits)));
1761 check(BigUint::new(vec!(-1, -1 >> 1)), i64::MAX);
1763 assert_eq!(i64::MIN.to_biguint(), None);
1764 assert_eq!(BigUint::new(vec!(-1, -1 )).to_i64(), None);
1765 assert_eq!(BigUint::new(vec!( 0, 0, 1)).to_i64(), None);
1766 assert_eq!(BigUint::new(vec!(-1, -1, -1)).to_i64(), None);
1769 // `DoubleBigDigit` size dependent
1771 fn test_convert_u64() {
1772 fn check(b1: BigUint, u: u64) {
1773 let b2: BigUint = FromPrimitive::from_u64(u).unwrap();
1775 assert!(b1.to_u64().unwrap() == u);
1778 check(Zero::zero(), 0);
1779 check(One::one(), 1);
1780 check(u64::MIN.to_biguint().unwrap(), u64::MIN);
1781 check(u64::MAX.to_biguint().unwrap(), u64::MAX);
1783 check(BigUint::new(vec!( )), 0);
1784 check(BigUint::new(vec!( 1 )), (1 << (0*BigDigit::bits)));
1785 check(BigUint::new(vec!(-1 )), (1 << (1*BigDigit::bits)) - 1);
1786 check(BigUint::new(vec!( 0, 1)), (1 << (1*BigDigit::bits)));
1787 check(BigUint::new(vec!(-1, -1)), u64::MAX);
1789 assert_eq!(BigUint::new(vec!( 0, 0, 1)).to_u64(), None);
1790 assert_eq!(BigUint::new(vec!(-1, -1, -1)).to_u64(), None);
1794 fn test_convert_to_bigint() {
1795 fn check(n: BigUint, ans: BigInt) {
1796 assert_eq!(n.to_bigint().unwrap(), ans);
1797 assert_eq!(n.to_bigint().unwrap().to_biguint().unwrap(), n);
1799 check(Zero::zero(), Zero::zero());
1800 check(BigUint::new(vec!(1,2,3)),
1801 BigInt::from_biguint(Plus, BigUint::new(vec!(1,2,3))));
1804 static sum_triples: &'static [(&'static [BigDigit],
1805 &'static [BigDigit],
1806 &'static [BigDigit])] = &[
1808 (&[], &[ 1], &[ 1]),
1809 (&[ 1], &[ 1], &[ 2]),
1810 (&[ 1], &[ 1, 1], &[ 2, 1]),
1811 (&[ 1], &[-1], &[ 0, 1]),
1812 (&[ 1], &[-1, -1], &[ 0, 0, 1]),
1813 (&[-1, -1], &[-1, -1], &[-2, -1, 1]),
1814 (&[ 1, 1, 1], &[-1, -1], &[ 0, 1, 2]),
1815 (&[ 2, 2, 1], &[-1, -2], &[ 1, 1, 2])
1820 for elm in sum_triples.iter() {
1821 let (a_vec, b_vec, c_vec) = *elm;
1822 let a = BigUint::from_slice(a_vec);
1823 let b = BigUint::from_slice(b_vec);
1824 let c = BigUint::from_slice(c_vec);
1826 assert!(a + b == c);
1827 assert!(b + a == c);
1833 for elm in sum_triples.iter() {
1834 let (a_vec, b_vec, c_vec) = *elm;
1835 let a = BigUint::from_slice(a_vec);
1836 let b = BigUint::from_slice(b_vec);
1837 let c = BigUint::from_slice(c_vec);
1839 assert!(c - a == b);
1840 assert!(c - b == a);
1846 fn test_sub_fail_on_underflow() {
1847 let (a, b) : (BigUint, BigUint) = (Zero::zero(), One::one());
1851 static mul_triples: &'static [(&'static [BigDigit],
1852 &'static [BigDigit],
1853 &'static [BigDigit])] = &[
1857 (&[ 1], &[ 1], &[1]),
1858 (&[ 2], &[ 3], &[ 6]),
1859 (&[ 1], &[ 1, 1, 1], &[1, 1, 1]),
1860 (&[ 1, 2, 3], &[ 3], &[ 3, 6, 9]),
1861 (&[ 1, 1, 1], &[-1], &[-1, -1, -1]),
1862 (&[ 1, 2, 3], &[-1], &[-1, -2, -2, 2]),
1863 (&[ 1, 2, 3, 4], &[-1], &[-1, -2, -2, -2, 3]),
1864 (&[-1], &[-1], &[ 1, -2]),
1865 (&[-1, -1], &[-1], &[ 1, -1, -2]),
1866 (&[-1, -1, -1], &[-1], &[ 1, -1, -1, -2]),
1867 (&[-1, -1, -1, -1], &[-1], &[ 1, -1, -1, -1, -2]),
1868 (&[-1/2 + 1], &[ 2], &[ 0, 1]),
1869 (&[0, -1/2 + 1], &[ 2], &[ 0, 0, 1]),
1870 (&[ 1, 2], &[ 1, 2, 3], &[1, 4, 7, 6]),
1871 (&[-1, -1], &[-1, -1, -1], &[1, 0, -1, -2, -1]),
1872 (&[-1, -1, -1], &[-1, -1, -1, -1], &[1, 0, 0, -1, -2, -1, -1]),
1873 (&[ 0, 0, 1], &[ 1, 2, 3], &[0, 0, 1, 2, 3]),
1874 (&[ 0, 0, 1], &[ 0, 0, 0, 1], &[0, 0, 0, 0, 0, 1])
1877 static div_rem_quadruples: &'static [(&'static [BigDigit],
1878 &'static [BigDigit],
1879 &'static [BigDigit],
1880 &'static [BigDigit])]
1882 (&[ 1], &[ 2], &[], &[1]),
1883 (&[ 1, 1], &[ 2], &[-1/2+1], &[1]),
1884 (&[ 1, 1, 1], &[ 2], &[-1/2+1, -1/2+1], &[1]),
1885 (&[ 0, 1], &[-1], &[1], &[1]),
1886 (&[-1, -1], &[-2], &[2, 1], &[3])
1891 for elm in mul_triples.iter() {
1892 let (a_vec, b_vec, c_vec) = *elm;
1893 let a = BigUint::from_slice(a_vec);
1894 let b = BigUint::from_slice(b_vec);
1895 let c = BigUint::from_slice(c_vec);
1897 assert!(a * b == c);
1898 assert!(b * a == c);
1901 for elm in div_rem_quadruples.iter() {
1902 let (a_vec, b_vec, c_vec, d_vec) = *elm;
1903 let a = BigUint::from_slice(a_vec);
1904 let b = BigUint::from_slice(b_vec);
1905 let c = BigUint::from_slice(c_vec);
1906 let d = BigUint::from_slice(d_vec);
1908 assert!(a == b * c + d);
1909 assert!(a == c * b + d);
1915 for elm in mul_triples.iter() {
1916 let (a_vec, b_vec, c_vec) = *elm;
1917 let a = BigUint::from_slice(a_vec);
1918 let b = BigUint::from_slice(b_vec);
1919 let c = BigUint::from_slice(c_vec);
1922 assert_eq!(c.div_rem(&a), (b.clone(), Zero::zero()));
1925 assert_eq!(c.div_rem(&b), (a.clone(), Zero::zero()));
1929 for elm in div_rem_quadruples.iter() {
1930 let (a_vec, b_vec, c_vec, d_vec) = *elm;
1931 let a = BigUint::from_slice(a_vec);
1932 let b = BigUint::from_slice(b_vec);
1933 let c = BigUint::from_slice(c_vec);
1934 let d = BigUint::from_slice(d_vec);
1936 if !b.is_zero() { assert!(a.div_rem(&b) == (c, d)); }
1941 fn test_checked_add() {
1942 for elm in sum_triples.iter() {
1943 let (aVec, bVec, cVec) = *elm;
1944 let a = BigUint::from_slice(aVec);
1945 let b = BigUint::from_slice(bVec);
1946 let c = BigUint::from_slice(cVec);
1948 assert!(a.checked_add(&b).unwrap() == c);
1949 assert!(b.checked_add(&a).unwrap() == c);
1954 fn test_checked_sub() {
1955 for elm in sum_triples.iter() {
1956 let (aVec, bVec, cVec) = *elm;
1957 let a = BigUint::from_slice(aVec);
1958 let b = BigUint::from_slice(bVec);
1959 let c = BigUint::from_slice(cVec);
1961 assert!(c.checked_sub(&a).unwrap() == b);
1962 assert!(c.checked_sub(&b).unwrap() == a);
1965 assert!(a.checked_sub(&c).is_none());
1968 assert!(b.checked_sub(&c).is_none());
1974 fn test_checked_mul() {
1975 for elm in mul_triples.iter() {
1976 let (aVec, bVec, cVec) = *elm;
1977 let a = BigUint::from_slice(aVec);
1978 let b = BigUint::from_slice(bVec);
1979 let c = BigUint::from_slice(cVec);
1981 assert!(a.checked_mul(&b).unwrap() == c);
1982 assert!(b.checked_mul(&a).unwrap() == c);
1985 for elm in div_rem_quadruples.iter() {
1986 let (aVec, bVec, cVec, dVec) = *elm;
1987 let a = BigUint::from_slice(aVec);
1988 let b = BigUint::from_slice(bVec);
1989 let c = BigUint::from_slice(cVec);
1990 let d = BigUint::from_slice(dVec);
1992 assert!(a == b.checked_mul(&c).unwrap() + d);
1993 assert!(a == c.checked_mul(&b).unwrap() + d);
1998 fn test_checked_div() {
1999 for elm in mul_triples.iter() {
2000 let (aVec, bVec, cVec) = *elm;
2001 let a = BigUint::from_slice(aVec);
2002 let b = BigUint::from_slice(bVec);
2003 let c = BigUint::from_slice(cVec);
2006 assert!(c.checked_div(&a).unwrap() == b);
2009 assert!(c.checked_div(&b).unwrap() == a);
2012 assert!(c.checked_div(&Zero::zero()).is_none());
2018 fn check(a: uint, b: uint, c: uint) {
2019 let big_a: BigUint = FromPrimitive::from_uint(a).unwrap();
2020 let big_b: BigUint = FromPrimitive::from_uint(b).unwrap();
2021 let big_c: BigUint = FromPrimitive::from_uint(c).unwrap();
2023 assert_eq!(big_a.gcd(&big_b), big_c);
2035 fn check(a: uint, b: uint, c: uint) {
2036 let big_a: BigUint = FromPrimitive::from_uint(a).unwrap();
2037 let big_b: BigUint = FromPrimitive::from_uint(b).unwrap();
2038 let big_c: BigUint = FromPrimitive::from_uint(c).unwrap();
2040 assert_eq!(big_a.lcm(&big_b), big_c);
2048 check(99, 17, 1683);
2053 let one: BigUint = FromStr::from_str("1").unwrap();
2054 let two: BigUint = FromStr::from_str("2").unwrap();
2055 let thousand: BigUint = FromStr::from_str("1000").unwrap();
2056 let big: BigUint = FromStr::from_str("1000000000000000000000").unwrap();
2057 let bigger: BigUint = FromStr::from_str("1000000000000000000001").unwrap();
2058 assert!(one.is_odd());
2059 assert!(two.is_even());
2060 assert!(thousand.is_even());
2061 assert!(big.is_even());
2062 assert!(bigger.is_odd());
2063 assert!((one << 64).is_even());
2064 assert!(((one << 64) + one).is_odd());
2067 fn to_str_pairs() -> Vec<(BigUint, Vec<(uint, String)>)> {
2068 let bits = BigDigit::bits;
2069 vec!(( Zero::zero(), vec!(
2070 (2, "0".to_string()), (3, "0".to_string())
2071 )), ( BigUint::from_slice([ 0xff ]), vec!(
2072 (2, "11111111".to_string()),
2073 (3, "100110".to_string()),
2074 (4, "3333".to_string()),
2075 (5, "2010".to_string()),
2076 (6, "1103".to_string()),
2077 (7, "513".to_string()),
2078 (8, "377".to_string()),
2079 (9, "313".to_string()),
2080 (10, "255".to_string()),
2081 (11, "212".to_string()),
2082 (12, "193".to_string()),
2083 (13, "168".to_string()),
2084 (14, "143".to_string()),
2085 (15, "120".to_string()),
2086 (16, "ff".to_string())
2087 )), ( BigUint::from_slice([ 0xfff ]), vec!(
2088 (2, "111111111111".to_string()),
2089 (4, "333333".to_string()),
2090 (16, "fff".to_string())
2091 )), ( BigUint::from_slice([ 1, 2 ]), vec!(
2093 format!("10{}1", "0".repeat(bits - 1))),
2095 format!("2{}1", "0".repeat(bits / 2 - 1))),
2097 32 => "8589934593".to_string(),
2098 16 => "131073".to_string(),
2102 format!("2{}1", "0".repeat(bits / 4 - 1)))
2103 )), ( BigUint::from_slice([ 1, 2, 3 ]), vec!(
2105 format!("11{}10{}1",
2106 "0".repeat(bits - 2),
2107 "0".repeat(bits - 1))),
2110 "0".repeat(bits / 2 - 1),
2111 "0".repeat(bits / 2 - 1))),
2113 32 => "55340232229718589441".to_string(),
2114 16 => "12885032961".to_string(),
2119 "0".repeat(bits / 4 - 1),
2120 "0".repeat(bits / 4 - 1)))
2125 fn test_to_str_radix() {
2126 let r = to_str_pairs();
2127 for num_pair in r.iter() {
2128 let &(ref n, ref rs) = num_pair;
2129 for str_pair in rs.iter() {
2130 let &(ref radix, ref str) = str_pair;
2131 assert_eq!(n.to_str_radix(*radix).as_slice(),
2138 fn test_from_str_radix() {
2139 let r = to_str_pairs();
2140 for num_pair in r.iter() {
2141 let &(ref n, ref rs) = num_pair;
2142 for str_pair in rs.iter() {
2143 let &(ref radix, ref str) = str_pair;
2145 &FromStrRadix::from_str_radix(str.as_slice(),
2150 let zed: Option<BigUint> = FromStrRadix::from_str_radix("Z", 10);
2151 assert_eq!(zed, None);
2152 let blank: Option<BigUint> = FromStrRadix::from_str_radix("_", 2);
2153 assert_eq!(blank, None);
2154 let minus_one: Option<BigUint> = FromStrRadix::from_str_radix("-1",
2156 assert_eq!(minus_one, None);
2161 fn factor(n: uint) -> BigUint {
2162 let mut f: BigUint = One::one();
2163 for i in range(2, n + 1) {
2164 // FIXME(#5992): assignment operator overloads
2165 // f *= FromPrimitive::from_uint(i);
2166 f = f * FromPrimitive::from_uint(i).unwrap();
2171 fn check(n: uint, s: &str) {
2173 let ans = match FromStrRadix::from_str_radix(s, 10) {
2174 Some(x) => x, None => fail!()
2180 check(10, "3628800");
2181 check(20, "2432902008176640000");
2182 check(30, "265252859812191058636308480000000");
2187 assert_eq!(BigUint::new(vec!(0,0,0,0)).bits(), 0);
2188 let n: BigUint = FromPrimitive::from_uint(0).unwrap();
2189 assert_eq!(n.bits(), 0);
2190 let n: BigUint = FromPrimitive::from_uint(1).unwrap();
2191 assert_eq!(n.bits(), 1);
2192 let n: BigUint = FromPrimitive::from_uint(3).unwrap();
2193 assert_eq!(n.bits(), 2);
2194 let n: BigUint = FromStrRadix::from_str_radix("4000000000", 16).unwrap();
2195 assert_eq!(n.bits(), 39);
2196 let one: BigUint = One::one();
2197 assert_eq!((one << 426).bits(), 427);
2202 let mut rng = task_rng();
2203 let _n: BigUint = rng.gen_biguint(137);
2204 assert!(rng.gen_biguint(0).is_zero());
2208 fn test_rand_range() {
2209 let mut rng = task_rng();
2211 for _ in range(0u, 10) {
2212 assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_uint(236).unwrap(),
2213 &FromPrimitive::from_uint(237).unwrap()),
2214 FromPrimitive::from_uint(236).unwrap());
2217 let l = FromPrimitive::from_uint(403469000 + 2352).unwrap();
2218 let u = FromPrimitive::from_uint(403469000 + 3513).unwrap();
2219 for _ in range(0u, 1000) {
2220 let n: BigUint = rng.gen_biguint_below(&u);
2223 let n: BigUint = rng.gen_biguint_range(&l, &u);
2231 fn test_zero_rand_range() {
2232 task_rng().gen_biguint_range(&FromPrimitive::from_uint(54).unwrap(),
2233 &FromPrimitive::from_uint(54).unwrap());
2238 fn test_negative_rand_range() {
2239 let mut rng = task_rng();
2240 let l = FromPrimitive::from_uint(2352).unwrap();
2241 let u = FromPrimitive::from_uint(3513).unwrap();
2242 // Switching u and l should fail:
2243 let _n: BigUint = rng.gen_biguint_range(&u, &l);
2250 use super::{BigDigit, BigUint, ToBigUint};
2251 use super::{Sign, Minus, Zero, Plus, BigInt, RandBigInt, ToBigInt};
2253 use std::cmp::{Less, Equal, Greater};
2255 use std::num::CheckedDiv;
2256 use std::num::{Zero, One, FromStrRadix, ToStrRadix};
2257 use std::num::{ToPrimitive, FromPrimitive};
2258 use std::rand::task_rng;
2262 fn test_from_biguint() {
2263 fn check(inp_s: Sign, inp_n: uint, ans_s: Sign, ans_n: uint) {
2264 let inp = BigInt::from_biguint(inp_s, FromPrimitive::from_uint(inp_n).unwrap());
2265 let ans = BigInt { sign: ans_s, data: FromPrimitive::from_uint(ans_n).unwrap()};
2266 assert_eq!(inp, ans);
2268 check(Plus, 1, Plus, 1);
2269 check(Plus, 0, Zero, 0);
2270 check(Minus, 1, Minus, 1);
2271 check(Zero, 1, Zero, 0);
2276 let vs = [ &[2 as BigDigit], &[1, 1], &[2, 1], &[1, 1, 1] ];
2277 let mut nums = Vec::new();
2278 for s in vs.iter().rev() {
2279 nums.push(BigInt::from_slice(Minus, *s));
2281 nums.push(Zero::zero());
2282 nums.extend(vs.iter().map(|s| BigInt::from_slice(Plus, *s)));
2284 for (i, ni) in nums.iter().enumerate() {
2285 for (j0, nj) in nums.slice(i, nums.len()).iter().enumerate() {
2288 assert_eq!(ni.cmp(nj), Equal);
2289 assert_eq!(nj.cmp(ni), Equal);
2291 assert!(!(ni != nj));
2294 assert!(!(ni < nj));
2295 assert!(!(ni > nj));
2297 assert_eq!(ni.cmp(nj), Less);
2298 assert_eq!(nj.cmp(ni), Greater);
2300 assert!(!(ni == nj));
2304 assert!(!(ni >= nj));
2306 assert!(!(ni > nj));
2308 assert!(!(nj <= ni));
2310 assert!(!(nj < ni));
2318 fn test_convert_i64() {
2319 fn check(b1: BigInt, i: i64) {
2320 let b2: BigInt = FromPrimitive::from_i64(i).unwrap();
2322 assert!(b1.to_i64().unwrap() == i);
2325 check(Zero::zero(), 0);
2326 check(One::one(), 1);
2327 check(i64::MIN.to_bigint().unwrap(), i64::MIN);
2328 check(i64::MAX.to_bigint().unwrap(), i64::MAX);
2331 (i64::MAX as u64 + 1).to_bigint().unwrap().to_i64(),
2335 BigInt::from_biguint(Plus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_i64(),
2339 BigInt::from_biguint(Minus, BigUint::new(vec!(1,0,0,1<<(BigDigit::bits-1)))).to_i64(),
2343 BigInt::from_biguint(Minus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_i64(),
2348 fn test_convert_u64() {
2349 fn check(b1: BigInt, u: u64) {
2350 let b2: BigInt = FromPrimitive::from_u64(u).unwrap();
2352 assert!(b1.to_u64().unwrap() == u);
2355 check(Zero::zero(), 0);
2356 check(One::one(), 1);
2357 check(u64::MIN.to_bigint().unwrap(), u64::MIN);
2358 check(u64::MAX.to_bigint().unwrap(), u64::MAX);
2361 BigInt::from_biguint(Plus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_u64(),
2364 let max_value: BigUint = FromPrimitive::from_u64(u64::MAX).unwrap();
2365 assert_eq!(BigInt::from_biguint(Minus, max_value).to_u64(), None);
2366 assert_eq!(BigInt::from_biguint(Minus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_u64(), None);
2370 fn test_convert_to_biguint() {
2371 fn check(n: BigInt, ans_1: BigUint) {
2372 assert_eq!(n.to_biguint().unwrap(), ans_1);
2373 assert_eq!(n.to_biguint().unwrap().to_bigint().unwrap(), n);
2375 let zero: BigInt = Zero::zero();
2376 let unsigned_zero: BigUint = Zero::zero();
2377 let positive = BigInt::from_biguint(
2378 Plus, BigUint::new(vec!(1,2,3)));
2379 let negative = -positive;
2381 check(zero, unsigned_zero);
2382 check(positive, BigUint::new(vec!(1,2,3)));
2384 assert_eq!(negative.to_biguint(), None);
2387 static sum_triples: &'static [(&'static [BigDigit],
2388 &'static [BigDigit],
2389 &'static [BigDigit])] = &[
2391 (&[], &[ 1], &[ 1]),
2392 (&[ 1], &[ 1], &[ 2]),
2393 (&[ 1], &[ 1, 1], &[ 2, 1]),
2394 (&[ 1], &[-1], &[ 0, 1]),
2395 (&[ 1], &[-1, -1], &[ 0, 0, 1]),
2396 (&[-1, -1], &[-1, -1], &[-2, -1, 1]),
2397 (&[ 1, 1, 1], &[-1, -1], &[ 0, 1, 2]),
2398 (&[ 2, 2, 1], &[-1, -2], &[ 1, 1, 2])
2403 for elm in sum_triples.iter() {
2404 let (a_vec, b_vec, c_vec) = *elm;
2405 let a = BigInt::from_slice(Plus, a_vec);
2406 let b = BigInt::from_slice(Plus, b_vec);
2407 let c = BigInt::from_slice(Plus, c_vec);
2409 assert!(a + b == c);
2410 assert!(b + a == c);
2411 assert!(c + (-a) == b);
2412 assert!(c + (-b) == a);
2413 assert!(a + (-c) == (-b));
2414 assert!(b + (-c) == (-a));
2415 assert!((-a) + (-b) == (-c))
2416 assert!(a + (-a) == Zero::zero());
2422 for elm in sum_triples.iter() {
2423 let (a_vec, b_vec, c_vec) = *elm;
2424 let a = BigInt::from_slice(Plus, a_vec);
2425 let b = BigInt::from_slice(Plus, b_vec);
2426 let c = BigInt::from_slice(Plus, c_vec);
2428 assert!(c - a == b);
2429 assert!(c - b == a);
2430 assert!((-b) - a == (-c))
2431 assert!((-a) - b == (-c))
2432 assert!(b - (-a) == c);
2433 assert!(a - (-b) == c);
2434 assert!((-c) - (-a) == (-b));
2435 assert!(a - a == Zero::zero());
2439 static mul_triples: &'static [(&'static [BigDigit],
2440 &'static [BigDigit],
2441 &'static [BigDigit])] = &[
2445 (&[ 1], &[ 1], &[1]),
2446 (&[ 2], &[ 3], &[ 6]),
2447 (&[ 1], &[ 1, 1, 1], &[1, 1, 1]),
2448 (&[ 1, 2, 3], &[ 3], &[ 3, 6, 9]),
2449 (&[ 1, 1, 1], &[-1], &[-1, -1, -1]),
2450 (&[ 1, 2, 3], &[-1], &[-1, -2, -2, 2]),
2451 (&[ 1, 2, 3, 4], &[-1], &[-1, -2, -2, -2, 3]),
2452 (&[-1], &[-1], &[ 1, -2]),
2453 (&[-1, -1], &[-1], &[ 1, -1, -2]),
2454 (&[-1, -1, -1], &[-1], &[ 1, -1, -1, -2]),
2455 (&[-1, -1, -1, -1], &[-1], &[ 1, -1, -1, -1, -2]),
2456 (&[-1/2 + 1], &[ 2], &[ 0, 1]),
2457 (&[0, -1/2 + 1], &[ 2], &[ 0, 0, 1]),
2458 (&[ 1, 2], &[ 1, 2, 3], &[1, 4, 7, 6]),
2459 (&[-1, -1], &[-1, -1, -1], &[1, 0, -1, -2, -1]),
2460 (&[-1, -1, -1], &[-1, -1, -1, -1], &[1, 0, 0, -1, -2, -1, -1]),
2461 (&[ 0, 0, 1], &[ 1, 2, 3], &[0, 0, 1, 2, 3]),
2462 (&[ 0, 0, 1], &[ 0, 0, 0, 1], &[0, 0, 0, 0, 0, 1])
2465 static div_rem_quadruples: &'static [(&'static [BigDigit],
2466 &'static [BigDigit],
2467 &'static [BigDigit],
2468 &'static [BigDigit])]
2470 (&[ 1], &[ 2], &[], &[1]),
2471 (&[ 1, 1], &[ 2], &[-1/2+1], &[1]),
2472 (&[ 1, 1, 1], &[ 2], &[-1/2+1, -1/2+1], &[1]),
2473 (&[ 0, 1], &[-1], &[1], &[1]),
2474 (&[-1, -1], &[-2], &[2, 1], &[3])
2479 for elm in mul_triples.iter() {
2480 let (a_vec, b_vec, c_vec) = *elm;
2481 let a = BigInt::from_slice(Plus, a_vec);
2482 let b = BigInt::from_slice(Plus, b_vec);
2483 let c = BigInt::from_slice(Plus, c_vec);
2485 assert!(a * b == c);
2486 assert!(b * a == c);
2488 assert!((-a) * b == -c);
2489 assert!((-b) * a == -c);
2492 for elm in div_rem_quadruples.iter() {
2493 let (a_vec, b_vec, c_vec, d_vec) = *elm;
2494 let a = BigInt::from_slice(Plus, a_vec);
2495 let b = BigInt::from_slice(Plus, b_vec);
2496 let c = BigInt::from_slice(Plus, c_vec);
2497 let d = BigInt::from_slice(Plus, d_vec);
2499 assert!(a == b * c + d);
2500 assert!(a == c * b + d);
2505 fn test_div_mod_floor() {
2506 fn check_sub(a: &BigInt, b: &BigInt, ans_d: &BigInt, ans_m: &BigInt) {
2507 let (d, m) = a.div_mod_floor(b);
2509 assert_eq!(m.sign, b.sign);
2511 assert!(m.abs() <= b.abs());
2512 assert!(*a == b * d + m);
2513 assert!(d == *ans_d);
2514 assert!(m == *ans_m);
2517 fn check(a: &BigInt, b: &BigInt, d: &BigInt, m: &BigInt) {
2519 check_sub(a, b, d, m);
2520 check_sub(a, &b.neg(), &d.neg(), m);
2521 check_sub(&a.neg(), b, &d.neg(), m);
2522 check_sub(&a.neg(), &b.neg(), d, m);
2524 check_sub(a, b, d, m);
2525 check_sub(a, &b.neg(), &(d.neg() - One::one()), &(m - *b));
2526 check_sub(&a.neg(), b, &(d.neg() - One::one()), &(b - *m));
2527 check_sub(&a.neg(), &b.neg(), d, &m.neg());
2531 for elm in mul_triples.iter() {
2532 let (a_vec, b_vec, c_vec) = *elm;
2533 let a = BigInt::from_slice(Plus, a_vec);
2534 let b = BigInt::from_slice(Plus, b_vec);
2535 let c = BigInt::from_slice(Plus, c_vec);
2537 if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); }
2538 if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); }
2541 for elm in div_rem_quadruples.iter() {
2542 let (a_vec, b_vec, c_vec, d_vec) = *elm;
2543 let a = BigInt::from_slice(Plus, a_vec);
2544 let b = BigInt::from_slice(Plus, b_vec);
2545 let c = BigInt::from_slice(Plus, c_vec);
2546 let d = BigInt::from_slice(Plus, d_vec);
2549 check(&a, &b, &c, &d);
2557 fn check_sub(a: &BigInt, b: &BigInt, ans_q: &BigInt, ans_r: &BigInt) {
2558 let (q, r) = a.div_rem(b);
2560 assert_eq!(r.sign, a.sign);
2562 assert!(r.abs() <= b.abs());
2563 assert!(*a == b * q + r);
2564 assert!(q == *ans_q);
2565 assert!(r == *ans_r);
2568 fn check(a: &BigInt, b: &BigInt, q: &BigInt, r: &BigInt) {
2569 check_sub(a, b, q, r);
2570 check_sub(a, &b.neg(), &q.neg(), r);
2571 check_sub(&a.neg(), b, &q.neg(), &r.neg());
2572 check_sub(&a.neg(), &b.neg(), q, &r.neg());
2574 for elm in mul_triples.iter() {
2575 let (a_vec, b_vec, c_vec) = *elm;
2576 let a = BigInt::from_slice(Plus, a_vec);
2577 let b = BigInt::from_slice(Plus, b_vec);
2578 let c = BigInt::from_slice(Plus, c_vec);
2580 if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); }
2581 if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); }
2584 for elm in div_rem_quadruples.iter() {
2585 let (a_vec, b_vec, c_vec, d_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);
2589 let d = BigInt::from_slice(Plus, d_vec);
2592 check(&a, &b, &c, &d);
2598 fn test_checked_add() {
2599 for elm in sum_triples.iter() {
2600 let (aVec, bVec, cVec) = *elm;
2601 let a = BigInt::from_slice(Plus, aVec);
2602 let b = BigInt::from_slice(Plus, bVec);
2603 let c = BigInt::from_slice(Plus, cVec);
2605 assert!(a.checked_add(&b).unwrap() == c);
2606 assert!(b.checked_add(&a).unwrap() == c);
2607 assert!(c.checked_add(&(-a)).unwrap() == b);
2608 assert!(c.checked_add(&(-b)).unwrap() == a);
2609 assert!(a.checked_add(&(-c)).unwrap() == (-b));
2610 assert!(b.checked_add(&(-c)).unwrap() == (-a));
2611 assert!((-a).checked_add(&(-b)).unwrap() == (-c))
2612 assert!(a.checked_add(&(-a)).unwrap() == Zero::zero());
2617 fn test_checked_sub() {
2618 for elm in sum_triples.iter() {
2619 let (aVec, bVec, cVec) = *elm;
2620 let a = BigInt::from_slice(Plus, aVec);
2621 let b = BigInt::from_slice(Plus, bVec);
2622 let c = BigInt::from_slice(Plus, cVec);
2624 assert!(c.checked_sub(&a).unwrap() == b);
2625 assert!(c.checked_sub(&b).unwrap() == a);
2626 assert!((-b).checked_sub(&a).unwrap() == (-c))
2627 assert!((-a).checked_sub(&b).unwrap() == (-c))
2628 assert!(b.checked_sub(&(-a)).unwrap() == c);
2629 assert!(a.checked_sub(&(-b)).unwrap() == c);
2630 assert!((-c).checked_sub(&(-a)).unwrap() == (-b));
2631 assert!(a.checked_sub(&a).unwrap() == Zero::zero());
2636 fn test_checked_mul() {
2637 for elm in mul_triples.iter() {
2638 let (aVec, bVec, cVec) = *elm;
2639 let a = BigInt::from_slice(Plus, aVec);
2640 let b = BigInt::from_slice(Plus, bVec);
2641 let c = BigInt::from_slice(Plus, cVec);
2643 assert!(a.checked_mul(&b).unwrap() == c);
2644 assert!(b.checked_mul(&a).unwrap() == c);
2646 assert!((-a).checked_mul(&b).unwrap() == -c);
2647 assert!((-b).checked_mul(&a).unwrap() == -c);
2650 for elm in div_rem_quadruples.iter() {
2651 let (aVec, bVec, cVec, dVec) = *elm;
2652 let a = BigInt::from_slice(Plus, aVec);
2653 let b = BigInt::from_slice(Plus, bVec);
2654 let c = BigInt::from_slice(Plus, cVec);
2655 let d = BigInt::from_slice(Plus, dVec);
2657 assert!(a == b.checked_mul(&c).unwrap() + d);
2658 assert!(a == c.checked_mul(&b).unwrap() + d);
2662 fn test_checked_div() {
2663 for elm in mul_triples.iter() {
2664 let (aVec, bVec, cVec) = *elm;
2665 let a = BigInt::from_slice(Plus, aVec);
2666 let b = BigInt::from_slice(Plus, bVec);
2667 let c = BigInt::from_slice(Plus, cVec);
2670 assert!(c.checked_div(&a).unwrap() == b);
2671 assert!((-c).checked_div(&(-a)).unwrap() == b);
2672 assert!((-c).checked_div(&a).unwrap() == -b);
2675 assert!(c.checked_div(&b).unwrap() == a);
2676 assert!((-c).checked_div(&(-b)).unwrap() == a);
2677 assert!((-c).checked_div(&b).unwrap() == -a);
2680 assert!(c.checked_div(&Zero::zero()).is_none());
2681 assert!((-c).checked_div(&Zero::zero()).is_none());
2687 fn check(a: int, b: int, c: int) {
2688 let big_a: BigInt = FromPrimitive::from_int(a).unwrap();
2689 let big_b: BigInt = FromPrimitive::from_int(b).unwrap();
2690 let big_c: BigInt = FromPrimitive::from_int(c).unwrap();
2692 assert_eq!(big_a.gcd(&big_b), big_c);
2707 fn check(a: int, b: int, c: int) {
2708 let big_a: BigInt = FromPrimitive::from_int(a).unwrap();
2709 let big_b: BigInt = FromPrimitive::from_int(b).unwrap();
2710 let big_c: BigInt = FromPrimitive::from_int(c).unwrap();
2712 assert_eq!(big_a.lcm(&big_b), big_c);
2727 let zero: BigInt = Zero::zero();
2728 let one: BigInt = One::one();
2729 assert_eq!((-one).abs_sub(&one), zero);
2730 let one: BigInt = One::one();
2731 let zero: BigInt = Zero::zero();
2732 assert_eq!(one.abs_sub(&one), zero);
2733 let one: BigInt = One::one();
2734 let zero: BigInt = Zero::zero();
2735 assert_eq!(one.abs_sub(&zero), one);
2736 let one: BigInt = One::one();
2737 let two: BigInt = FromPrimitive::from_int(2).unwrap();
2738 assert_eq!(one.abs_sub(&-one), two);
2742 fn test_to_str_radix() {
2743 fn check(n: int, ans: &str) {
2744 let n: BigInt = FromPrimitive::from_int(n).unwrap();
2745 assert!(ans == n.to_str_radix(10).as_slice());
2756 fn test_from_str_radix() {
2757 fn check(s: &str, ans: Option<int>) {
2758 let ans = ans.map(|n| {
2759 let x: BigInt = FromPrimitive::from_int(n).unwrap();
2762 assert_eq!(FromStrRadix::from_str_radix(s, 10), ans);
2764 check("10", Some(10));
2765 check("1", Some(1));
2766 check("0", Some(0));
2767 check("-1", Some(-1));
2768 check("-10", Some(-10));
2772 // issue 10522, this hit an edge case that caused it to
2773 // attempt to allocate a vector of size (-1u) == huge.
2775 from_str(format!("1{}", "0".repeat(36)).as_slice()).unwrap();
2776 let _y = x.to_string();
2781 assert!(-BigInt::new(Plus, vec!(1, 1, 1)) ==
2782 BigInt::new(Minus, vec!(1, 1, 1)));
2783 assert!(-BigInt::new(Minus, vec!(1, 1, 1)) ==
2784 BigInt::new(Plus, vec!(1, 1, 1)));
2785 let zero: BigInt = Zero::zero();
2786 assert_eq!(-zero, zero);
2791 let mut rng = task_rng();
2792 let _n: BigInt = rng.gen_bigint(137);
2793 assert!(rng.gen_bigint(0).is_zero());
2797 fn test_rand_range() {
2798 let mut rng = task_rng();
2800 for _ in range(0u, 10) {
2801 assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_uint(236).unwrap(),
2802 &FromPrimitive::from_uint(237).unwrap()),
2803 FromPrimitive::from_uint(236).unwrap());
2806 fn check(l: BigInt, u: BigInt) {
2807 let mut rng = task_rng();
2808 for _ in range(0u, 1000) {
2809 let n: BigInt = rng.gen_bigint_range(&l, &u);
2814 let l: BigInt = FromPrimitive::from_uint(403469000 + 2352).unwrap();
2815 let u: BigInt = FromPrimitive::from_uint(403469000 + 3513).unwrap();
2816 check( l.clone(), u.clone());
2817 check(-l.clone(), u.clone());
2818 check(-u.clone(), -l.clone());
2823 fn test_zero_rand_range() {
2824 task_rng().gen_bigint_range(&FromPrimitive::from_int(54).unwrap(),
2825 &FromPrimitive::from_int(54).unwrap());
2830 fn test_negative_rand_range() {
2831 let mut rng = task_rng();
2832 let l = FromPrimitive::from_uint(2352).unwrap();
2833 let u = FromPrimitive::from_uint(3513).unwrap();
2834 // Switching u and l should fail:
2835 let _n: BigInt = rng.gen_bigint_range(&u, &l);
2842 use self::test::Bencher;
2845 use std::mem::replace;
2846 use std::num::{FromPrimitive, Zero, One};
2848 fn factorial(n: uint) -> BigUint {
2849 let mut f: BigUint = One::one();
2850 for i in iter::range_inclusive(1, n) {
2851 f = f * FromPrimitive::from_uint(i).unwrap();
2856 fn fib(n: uint) -> BigUint {
2857 let mut f0: BigUint = Zero::zero();
2858 let mut f1: BigUint = One::one();
2859 for _ in range(0, n) {
2861 f0 = replace(&mut f1, f2);
2867 fn factorial_100(b: &mut Bencher) {
2874 fn fib_100(b: &mut Bencher) {
2881 fn to_string(b: &mut Bencher) {
2882 let fac = factorial(100);
2893 fn shr(b: &mut Bencher) {
2894 let n = { let one : BigUint = One::one(); one << 1000 };
2896 let mut m = n.clone();
2897 for _ in range(0u, 10) {