2014-09-16 17:35:35 +00:00
|
|
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
|
|
|
|
// file at the top-level directory of this distribution and at
|
|
|
|
// http://rust-lang.org/COPYRIGHT.
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
|
|
|
// option. This file may not be copied, modified, or distributed
|
|
|
|
// except according to those terms.
|
|
|
|
|
|
|
|
//! A Big integer (signed version: `BigInt`, unsigned version: `BigUint`).
|
|
|
|
//!
|
2015-04-15 19:43:37 +00:00
|
|
|
//! A `BigUint` is represented as a vector of `BigDigit`s.
|
2014-09-16 17:35:35 +00:00
|
|
|
//! A `BigInt` is a combination of `BigUint` and `Sign`.
|
|
|
|
//!
|
|
|
|
//! Common numerical operations are overloaded, so we can treat them
|
|
|
|
//! the same way we treat other numbers.
|
|
|
|
//!
|
|
|
|
//! ## Example
|
|
|
|
//!
|
|
|
|
//! ```rust
|
2014-11-15 03:30:48 +00:00
|
|
|
//! use num::{BigUint, Zero, One};
|
2014-09-16 17:35:35 +00:00
|
|
|
//! use std::mem::replace;
|
|
|
|
//!
|
|
|
|
//! // Calculate large fibonacci numbers.
|
2015-01-09 11:36:03 +00:00
|
|
|
//! fn fib(n: usize) -> BigUint {
|
2014-09-16 17:35:35 +00:00
|
|
|
//! let mut f0: BigUint = Zero::zero();
|
|
|
|
//! let mut f1: BigUint = One::one();
|
2015-10-19 13:43:47 +00:00
|
|
|
//! for _ in 0..n {
|
2014-12-16 14:38:35 +00:00
|
|
|
//! let f2 = f0 + &f1;
|
2014-09-16 17:35:35 +00:00
|
|
|
//! // This is a low cost way of swapping f0 with f1 and f1 with f2.
|
|
|
|
//! f0 = replace(&mut f1, f2);
|
|
|
|
//! }
|
|
|
|
//! f0
|
|
|
|
//! }
|
|
|
|
//!
|
|
|
|
//! // This is a very large number.
|
|
|
|
//! println!("fib(1000) = {}", fib(1000));
|
|
|
|
//! ```
|
|
|
|
//!
|
|
|
|
//! It's easy to generate large random numbers:
|
|
|
|
//!
|
|
|
|
//! ```rust
|
2015-02-05 16:20:16 +00:00
|
|
|
//! extern crate rand;
|
|
|
|
//! extern crate num;
|
|
|
|
//! # fn main() {
|
2014-09-16 17:35:35 +00:00
|
|
|
//! use num::bigint::{ToBigInt, RandBigInt};
|
|
|
|
//!
|
2015-01-01 17:07:52 +00:00
|
|
|
//! let mut rng = rand::thread_rng();
|
2015-01-09 11:36:03 +00:00
|
|
|
//! let a = rng.gen_bigint(1000);
|
2014-09-16 17:35:35 +00:00
|
|
|
//!
|
2015-01-09 11:36:03 +00:00
|
|
|
//! let low = -10000.to_bigint().unwrap();
|
|
|
|
//! let high = 10000.to_bigint().unwrap();
|
2014-09-16 17:35:35 +00:00
|
|
|
//! let b = rng.gen_bigint_range(&low, &high);
|
|
|
|
//!
|
|
|
|
//! // Probably an even larger number.
|
|
|
|
//! println!("{}", a * b);
|
2015-02-05 16:20:16 +00:00
|
|
|
//! # }
|
2014-09-16 17:35:35 +00:00
|
|
|
//! ```
|
|
|
|
|
|
|
|
use Integer;
|
|
|
|
|
|
|
|
use std::default::Default;
|
2015-04-02 10:37:57 +00:00
|
|
|
use std::error::Error;
|
2014-12-23 17:50:53 +00:00
|
|
|
use std::iter::repeat;
|
2015-04-03 06:29:17 +00:00
|
|
|
use std::num::ParseIntError;
|
2015-01-03 18:30:05 +00:00
|
|
|
use std::ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Rem, Shl, Shr, Sub};
|
|
|
|
use std::str::{self, FromStr};
|
2015-01-21 01:38:51 +00:00
|
|
|
use std::{cmp, fmt, hash, mem};
|
|
|
|
use std::cmp::Ordering::{self, Less, Greater, Equal};
|
2014-11-04 14:20:37 +00:00
|
|
|
use std::{i64, u64};
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2015-02-05 16:20:16 +00:00
|
|
|
use rand::Rng;
|
2015-01-21 01:38:51 +00:00
|
|
|
use rustc_serialize::hex::ToHex;
|
|
|
|
|
2015-11-09 20:50:25 +00:00
|
|
|
use traits::{ToPrimitive, FromPrimitive};
|
2015-04-03 06:29:17 +00:00
|
|
|
|
2014-11-15 03:30:48 +00:00
|
|
|
use {Num, Unsigned, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv, Signed, Zero, One};
|
2014-11-18 12:09:53 +00:00
|
|
|
use self::Sign::{Minus, NoSign, Plus};
|
2014-11-15 03:30:48 +00:00
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
/// A `BigDigit` is a `BigUint`'s composing element.
|
|
|
|
pub type BigDigit = u32;
|
|
|
|
|
|
|
|
/// A `DoubleBigDigit` is the internal type used to do the computations. Its
|
|
|
|
/// size is the double of the size of `BigDigit`.
|
|
|
|
pub type DoubleBigDigit = u64;
|
|
|
|
|
2014-10-10 13:50:22 +00:00
|
|
|
pub const ZERO_BIG_DIGIT: BigDigit = 0;
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
#[allow(non_snake_case)]
|
2015-01-20 19:17:41 +00:00
|
|
|
pub mod big_digit {
|
2014-09-16 17:35:35 +00:00
|
|
|
use super::BigDigit;
|
|
|
|
use super::DoubleBigDigit;
|
|
|
|
|
|
|
|
// `DoubleBigDigit` size dependent
|
2015-01-09 11:36:03 +00:00
|
|
|
pub const BITS: usize = 32;
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2014-11-07 03:47:10 +00:00
|
|
|
pub const BASE: DoubleBigDigit = 1 << BITS;
|
2015-04-03 06:29:17 +00:00
|
|
|
const LO_MASK: DoubleBigDigit = (-1i32 as DoubleBigDigit) >> BITS;
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
#[inline]
|
2014-11-07 03:47:10 +00:00
|
|
|
fn get_hi(n: DoubleBigDigit) -> BigDigit { (n >> BITS) as BigDigit }
|
2014-09-16 17:35:35 +00:00
|
|
|
#[inline]
|
2014-10-10 13:54:30 +00:00
|
|
|
fn get_lo(n: DoubleBigDigit) -> BigDigit { (n & LO_MASK) as BigDigit }
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
/// Split one `DoubleBigDigit` into two `BigDigit`s.
|
|
|
|
#[inline]
|
|
|
|
pub fn from_doublebigdigit(n: DoubleBigDigit) -> (BigDigit, BigDigit) {
|
|
|
|
(get_hi(n), get_lo(n))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Join two `BigDigit`s into one `DoubleBigDigit`
|
|
|
|
#[inline]
|
|
|
|
pub fn to_doublebigdigit(hi: BigDigit, lo: BigDigit) -> DoubleBigDigit {
|
2014-11-07 03:47:10 +00:00
|
|
|
(lo as DoubleBigDigit) | ((hi as DoubleBigDigit) << BITS)
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-12-10 21:33:28 +00:00
|
|
|
/*
|
|
|
|
* Generic functions for add/subtract/multiply with carry/borrow:
|
|
|
|
*/
|
|
|
|
|
|
|
|
// Add with carry:
|
|
|
|
#[inline]
|
|
|
|
fn adc(a: BigDigit, b: BigDigit, carry: &mut BigDigit) -> BigDigit {
|
|
|
|
let (hi, lo) = big_digit::from_doublebigdigit(
|
|
|
|
(a as DoubleBigDigit) +
|
|
|
|
(b as DoubleBigDigit) +
|
|
|
|
(*carry as DoubleBigDigit));
|
|
|
|
|
|
|
|
*carry = hi;
|
|
|
|
lo
|
|
|
|
}
|
|
|
|
|
|
|
|
// Subtract with borrow:
|
|
|
|
#[inline]
|
|
|
|
fn sbb(a: BigDigit, b: BigDigit, borrow: &mut BigDigit) -> BigDigit {
|
|
|
|
let (hi, lo) = big_digit::from_doublebigdigit(
|
|
|
|
big_digit::BASE
|
|
|
|
+ (a as DoubleBigDigit)
|
|
|
|
- (b as DoubleBigDigit)
|
|
|
|
- (*borrow as DoubleBigDigit));
|
|
|
|
/*
|
|
|
|
hi * (base) + lo == 1*(base) + ai - bi - borrow
|
|
|
|
=> ai - bi - borrow < 0 <=> hi == 0
|
|
|
|
*/
|
|
|
|
*borrow = if hi == 0 { 1 } else { 0 };
|
|
|
|
lo
|
|
|
|
}
|
|
|
|
|
Improve multiply performance
The main idea here is to do as much as possible with slices, instead of
allocating new BigUints (= heap allocations).
Current performance:
multiply_0: 10,507 ns/iter (+/- 987)
multiply_1: 2,788,734 ns/iter (+/- 100,079)
multiply_2: 69,923,515 ns/iter (+/- 4,550,902)
After this patch, we get:
multiply_0: 364 ns/iter (+/- 62)
multiply_1: 34,085 ns/iter (+/- 1,179)
multiply_2: 3,753,883 ns/iter (+/- 46,876)
2015-12-11 00:25:42 +00:00
|
|
|
#[inline]
|
|
|
|
fn mac_with_carry(a: BigDigit, b: BigDigit, c: BigDigit, carry: &mut BigDigit) -> BigDigit {
|
|
|
|
let (hi, lo) = big_digit::from_doublebigdigit(
|
|
|
|
(a as DoubleBigDigit) +
|
|
|
|
(b as DoubleBigDigit) * (c as DoubleBigDigit) +
|
|
|
|
(*carry as DoubleBigDigit));
|
|
|
|
*carry = hi;
|
|
|
|
lo
|
|
|
|
}
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
/// A big unsigned integer type.
|
|
|
|
///
|
|
|
|
/// A `BigUint`-typed value `BigUint { data: vec!(a, b, c) }` represents a number
|
2015-01-20 19:17:41 +00:00
|
|
|
/// `(a + b * big_digit::BASE + c * big_digit::BASE^2)`.
|
2015-01-23 16:54:55 +00:00
|
|
|
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
|
2014-09-16 17:35:35 +00:00
|
|
|
pub struct BigUint {
|
|
|
|
data: Vec<BigDigit>
|
|
|
|
}
|
|
|
|
|
|
|
|
impl PartialEq for BigUint {
|
|
|
|
#[inline]
|
|
|
|
fn eq(&self, other: &BigUint) -> bool {
|
|
|
|
match self.cmp(other) { Equal => true, _ => false }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
impl Eq for BigUint {}
|
|
|
|
|
|
|
|
impl PartialOrd for BigUint {
|
|
|
|
#[inline]
|
|
|
|
fn partial_cmp(&self, other: &BigUint) -> Option<Ordering> {
|
|
|
|
Some(self.cmp(other))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
Improve multiply performance
The main idea here is to do as much as possible with slices, instead of
allocating new BigUints (= heap allocations).
Current performance:
multiply_0: 10,507 ns/iter (+/- 987)
multiply_1: 2,788,734 ns/iter (+/- 100,079)
multiply_2: 69,923,515 ns/iter (+/- 4,550,902)
After this patch, we get:
multiply_0: 364 ns/iter (+/- 62)
multiply_1: 34,085 ns/iter (+/- 1,179)
multiply_2: 3,753,883 ns/iter (+/- 46,876)
2015-12-11 00:25:42 +00:00
|
|
|
fn cmp_slice(a: &[BigDigit], b: &[BigDigit]) -> Ordering {
|
|
|
|
debug_assert!(a.last() != Some(&0));
|
|
|
|
debug_assert!(b.last() != Some(&0));
|
|
|
|
|
|
|
|
let (a_len, b_len) = (a.len(), b.len());
|
|
|
|
if a_len < b_len { return Less; }
|
|
|
|
if a_len > b_len { return Greater; }
|
|
|
|
|
|
|
|
for (&ai, &bi) in a.iter().rev().zip(b.iter().rev()) {
|
|
|
|
if ai < bi { return Less; }
|
|
|
|
if ai > bi { return Greater; }
|
|
|
|
}
|
|
|
|
return Equal;
|
|
|
|
}
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
impl Ord for BigUint {
|
|
|
|
#[inline]
|
|
|
|
fn cmp(&self, other: &BigUint) -> Ordering {
|
Improve multiply performance
The main idea here is to do as much as possible with slices, instead of
allocating new BigUints (= heap allocations).
Current performance:
multiply_0: 10,507 ns/iter (+/- 987)
multiply_1: 2,788,734 ns/iter (+/- 100,079)
multiply_2: 69,923,515 ns/iter (+/- 4,550,902)
After this patch, we get:
multiply_0: 364 ns/iter (+/- 62)
multiply_1: 34,085 ns/iter (+/- 1,179)
multiply_2: 3,753,883 ns/iter (+/- 46,876)
2015-12-11 00:25:42 +00:00
|
|
|
cmp_slice(&self.data[..], &other.data[..])
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for BigUint {
|
|
|
|
#[inline]
|
|
|
|
fn default() -> BigUint { Zero::zero() }
|
|
|
|
}
|
|
|
|
|
2015-02-20 18:26:13 +00:00
|
|
|
impl hash::Hash for BigUint {
|
|
|
|
fn hash<H>(&self, state: &mut H) where H: hash::Hasher {
|
2014-09-16 17:35:35 +00:00
|
|
|
// hash 0 in case it's all 0's
|
|
|
|
0u32.hash(state);
|
|
|
|
|
|
|
|
let mut found_first_value = false;
|
|
|
|
for elem in self.data.iter().rev() {
|
|
|
|
// don't hash any leading 0's, they shouldn't affect the hash
|
|
|
|
if found_first_value || *elem != 0 {
|
|
|
|
found_first_value = true;
|
|
|
|
elem.hash(state);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-23 16:54:55 +00:00
|
|
|
impl fmt::Display for BigUint {
|
2015-01-09 11:36:03 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
2015-11-09 20:50:25 +00:00
|
|
|
write!(f, "{}", self.to_str_radix(10))
|
2015-01-09 11:36:03 +00:00
|
|
|
}
|
|
|
|
}
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
impl FromStr for BigUint {
|
2015-02-03 19:42:46 +00:00
|
|
|
type Err = ParseBigIntError;
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[inline]
|
2015-02-03 19:42:46 +00:00
|
|
|
fn from_str(s: &str) -> Result<BigUint, ParseBigIntError> {
|
2015-04-03 06:29:17 +00:00
|
|
|
BigUint::from_str_radix(s, 10)
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-04-03 06:29:17 +00:00
|
|
|
impl Num for BigUint {
|
|
|
|
type FromStrRadixErr = ParseBigIntError;
|
|
|
|
|
|
|
|
/// Creates and initializes a `BigUint`.
|
|
|
|
#[inline]
|
|
|
|
fn from_str_radix(s: &str, radix: u32) -> Result<BigUint, ParseBigIntError> {
|
|
|
|
let (base, unit_len) = get_radix_base(radix);
|
|
|
|
let base_num = match base.to_biguint() {
|
|
|
|
Some(base_num) => base_num,
|
|
|
|
None => { return Err(ParseBigIntError::Other); }
|
|
|
|
};
|
|
|
|
|
|
|
|
let mut end = s.len();
|
|
|
|
let mut n: BigUint = Zero::zero();
|
|
|
|
let mut power: BigUint = One::one();
|
|
|
|
loop {
|
|
|
|
let start = cmp::max(end, unit_len) - unit_len;
|
|
|
|
let d = try!(usize::from_str_radix(&s[start .. end], radix));
|
|
|
|
let d: Option<BigUint> = FromPrimitive::from_usize(d);
|
|
|
|
match d {
|
|
|
|
Some(d) => {
|
|
|
|
// FIXME(#5992): assignment operator overloads
|
|
|
|
// n += d * &power;
|
|
|
|
n = n + d * &power;
|
|
|
|
}
|
|
|
|
None => { return Err(ParseBigIntError::Other); }
|
|
|
|
}
|
|
|
|
if end <= unit_len {
|
|
|
|
return Ok(n);
|
|
|
|
}
|
|
|
|
end -= unit_len;
|
|
|
|
// FIXME(#5992): assignment operator overloads
|
|
|
|
// power *= &base_num;
|
|
|
|
power = power * &base_num;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2014-12-16 14:38:35 +00:00
|
|
|
macro_rules! forward_val_val_binop {
|
|
|
|
(impl $imp:ident for $res:ty, $method:ident) => {
|
2015-01-04 16:49:46 +00:00
|
|
|
impl $imp<$res> for $res {
|
|
|
|
type Output = $res;
|
|
|
|
|
2014-12-16 14:38:35 +00:00
|
|
|
#[inline]
|
|
|
|
fn $method(self, other: $res) -> $res {
|
2015-11-16 18:56:30 +00:00
|
|
|
// forward to val-ref
|
|
|
|
$imp::$method(self, &other)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
macro_rules! forward_val_val_binop_commutative {
|
|
|
|
(impl $imp:ident for $res:ty, $method:ident) => {
|
|
|
|
impl $imp<$res> for $res {
|
|
|
|
type Output = $res;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn $method(self, other: $res) -> $res {
|
|
|
|
// forward to val-ref, with the larger capacity as val
|
|
|
|
if self.data.capacity() >= other.data.capacity() {
|
|
|
|
$imp::$method(self, &other)
|
|
|
|
} else {
|
|
|
|
$imp::$method(other, &self)
|
|
|
|
}
|
2014-12-16 14:38:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
macro_rules! forward_ref_val_binop {
|
|
|
|
(impl $imp:ident for $res:ty, $method:ident) => {
|
2015-01-04 16:49:46 +00:00
|
|
|
impl<'a> $imp<$res> for &'a $res {
|
|
|
|
type Output = $res;
|
|
|
|
|
2014-12-16 14:38:35 +00:00
|
|
|
#[inline]
|
|
|
|
fn $method(self, other: $res) -> $res {
|
2015-11-16 18:56:30 +00:00
|
|
|
// forward to ref-ref
|
|
|
|
$imp::$method(self, &other)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
macro_rules! forward_ref_val_binop_commutative {
|
|
|
|
(impl $imp:ident for $res:ty, $method:ident) => {
|
|
|
|
impl<'a> $imp<$res> for &'a $res {
|
|
|
|
type Output = $res;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn $method(self, other: $res) -> $res {
|
|
|
|
// reverse, forward to val-ref
|
|
|
|
$imp::$method(other, self)
|
2014-12-16 14:38:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
macro_rules! forward_val_ref_binop {
|
|
|
|
(impl $imp:ident for $res:ty, $method:ident) => {
|
2015-01-04 16:49:46 +00:00
|
|
|
impl<'a> $imp<&'a $res> for $res {
|
|
|
|
type Output = $res;
|
|
|
|
|
2014-12-16 14:38:35 +00:00
|
|
|
#[inline]
|
|
|
|
fn $method(self, other: &$res) -> $res {
|
2015-11-16 18:56:30 +00:00
|
|
|
// forward to ref-ref
|
|
|
|
$imp::$method(&self, other)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
macro_rules! forward_ref_ref_binop {
|
|
|
|
(impl $imp:ident for $res:ty, $method:ident) => {
|
|
|
|
impl<'a, 'b> $imp<&'b $res> for &'a $res {
|
|
|
|
type Output = $res;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn $method(self, other: &$res) -> $res {
|
|
|
|
// forward to val-ref
|
|
|
|
$imp::$method(self.clone(), other)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
macro_rules! forward_ref_ref_binop_commutative {
|
|
|
|
(impl $imp:ident for $res:ty, $method:ident) => {
|
|
|
|
impl<'a, 'b> $imp<&'b $res> for &'a $res {
|
|
|
|
type Output = $res;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn $method(self, other: &$res) -> $res {
|
|
|
|
// forward to val-ref, choosing the larger to clone
|
|
|
|
if self.data.len() >= other.data.len() {
|
|
|
|
$imp::$method(self.clone(), other)
|
|
|
|
} else {
|
|
|
|
$imp::$method(other.clone(), self)
|
|
|
|
}
|
2014-12-16 14:38:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-16 18:56:30 +00:00
|
|
|
// Forward everything to ref-ref, when reusing storage is not helpful
|
|
|
|
macro_rules! forward_all_binop_to_ref_ref {
|
2014-12-16 14:38:35 +00:00
|
|
|
(impl $imp:ident for $res:ty, $method:ident) => {
|
2014-12-19 02:01:24 +00:00
|
|
|
forward_val_val_binop!(impl $imp for $res, $method);
|
|
|
|
forward_val_ref_binop!(impl $imp for $res, $method);
|
2015-11-16 18:56:30 +00:00
|
|
|
forward_ref_val_binop!(impl $imp for $res, $method);
|
2014-12-16 14:38:35 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2015-11-16 18:56:30 +00:00
|
|
|
// Forward everything to val-ref, so LHS storage can be reused
|
|
|
|
macro_rules! forward_all_binop_to_val_ref {
|
|
|
|
(impl $imp:ident for $res:ty, $method:ident) => {
|
|
|
|
forward_val_val_binop!(impl $imp for $res, $method);
|
|
|
|
forward_ref_val_binop!(impl $imp for $res, $method);
|
|
|
|
forward_ref_ref_binop!(impl $imp for $res, $method);
|
|
|
|
};
|
|
|
|
}
|
2014-12-16 14:38:35 +00:00
|
|
|
|
2015-11-16 18:56:30 +00:00
|
|
|
// Forward everything to val-ref, commutatively, so either LHS or RHS storage can be reused
|
|
|
|
macro_rules! forward_all_binop_to_val_ref_commutative {
|
|
|
|
(impl $imp:ident for $res:ty, $method:ident) => {
|
|
|
|
forward_val_val_binop_commutative!(impl $imp for $res, $method);
|
|
|
|
forward_ref_val_binop_commutative!(impl $imp for $res, $method);
|
|
|
|
forward_ref_ref_binop_commutative!(impl $imp for $res, $method);
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
forward_all_binop_to_val_ref_commutative!(impl BitAnd for BigUint, bitand);
|
|
|
|
|
|
|
|
impl<'a> BitAnd<&'a BigUint> for BigUint {
|
2015-01-04 16:49:46 +00:00
|
|
|
type Output = BigUint;
|
|
|
|
|
2014-12-16 14:38:35 +00:00
|
|
|
#[inline]
|
|
|
|
fn bitand(self, other: &BigUint) -> BigUint {
|
2015-11-16 18:56:30 +00:00
|
|
|
let mut data = self.data;
|
|
|
|
for (ai, &bi) in data.iter_mut().zip(other.data.iter()) {
|
|
|
|
*ai &= bi;
|
|
|
|
}
|
|
|
|
data.truncate(other.data.len());
|
|
|
|
BigUint::new(data)
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-16 18:56:30 +00:00
|
|
|
forward_all_binop_to_val_ref_commutative!(impl BitOr for BigUint, bitor);
|
2014-12-16 14:38:35 +00:00
|
|
|
|
2015-11-16 18:56:30 +00:00
|
|
|
impl<'a> BitOr<&'a BigUint> for BigUint {
|
2015-01-04 16:49:46 +00:00
|
|
|
type Output = BigUint;
|
|
|
|
|
2014-12-16 14:38:35 +00:00
|
|
|
fn bitor(self, other: &BigUint) -> BigUint {
|
2015-11-16 18:56:30 +00:00
|
|
|
let mut data = self.data;
|
|
|
|
for (ai, &bi) in data.iter_mut().zip(other.data.iter()) {
|
|
|
|
*ai |= bi;
|
|
|
|
}
|
|
|
|
if other.data.len() > data.len() {
|
|
|
|
let extra = &other.data[data.len()..];
|
|
|
|
data.extend(extra.iter().cloned());
|
|
|
|
}
|
|
|
|
BigUint::new(data)
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-16 18:56:30 +00:00
|
|
|
forward_all_binop_to_val_ref_commutative!(impl BitXor for BigUint, bitxor);
|
2014-12-16 14:38:35 +00:00
|
|
|
|
2015-11-16 18:56:30 +00:00
|
|
|
impl<'a> BitXor<&'a BigUint> for BigUint {
|
2015-01-04 16:49:46 +00:00
|
|
|
type Output = BigUint;
|
|
|
|
|
2014-12-16 14:38:35 +00:00
|
|
|
fn bitxor(self, other: &BigUint) -> BigUint {
|
2015-11-16 18:56:30 +00:00
|
|
|
let mut data = self.data;
|
|
|
|
for (ai, &bi) in data.iter_mut().zip(other.data.iter()) {
|
|
|
|
*ai ^= bi;
|
|
|
|
}
|
|
|
|
if other.data.len() > data.len() {
|
|
|
|
let extra = &other.data[data.len()..];
|
|
|
|
data.extend(extra.iter().cloned());
|
|
|
|
}
|
|
|
|
BigUint::new(data)
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-09 11:36:03 +00:00
|
|
|
impl Shl<usize> for BigUint {
|
2015-01-04 16:49:46 +00:00
|
|
|
type Output = BigUint;
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[inline]
|
2015-01-09 11:36:03 +00:00
|
|
|
fn shl(self, rhs: usize) -> BigUint { (&self) << rhs }
|
2014-12-16 14:38:35 +00:00
|
|
|
}
|
|
|
|
|
2015-01-09 11:36:03 +00:00
|
|
|
impl<'a> Shl<usize> for &'a BigUint {
|
2015-01-04 16:49:46 +00:00
|
|
|
type Output = BigUint;
|
|
|
|
|
2014-12-16 14:38:35 +00:00
|
|
|
#[inline]
|
2015-01-09 11:36:03 +00:00
|
|
|
fn shl(self, rhs: usize) -> BigUint {
|
2015-01-20 19:17:41 +00:00
|
|
|
let n_unit = rhs / big_digit::BITS;
|
|
|
|
let n_bits = rhs % big_digit::BITS;
|
2015-11-16 18:56:30 +00:00
|
|
|
self.shl_unit(n_unit).shl_bits(n_bits)
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-09 11:36:03 +00:00
|
|
|
impl Shr<usize> for BigUint {
|
2015-01-04 16:49:46 +00:00
|
|
|
type Output = BigUint;
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[inline]
|
2015-01-09 11:36:03 +00:00
|
|
|
fn shr(self, rhs: usize) -> BigUint { (&self) >> rhs }
|
2014-12-16 14:38:35 +00:00
|
|
|
}
|
|
|
|
|
2015-01-09 11:36:03 +00:00
|
|
|
impl<'a> Shr<usize> for &'a BigUint {
|
2015-01-04 16:49:46 +00:00
|
|
|
type Output = BigUint;
|
|
|
|
|
2014-12-16 14:38:35 +00:00
|
|
|
#[inline]
|
2015-01-09 11:36:03 +00:00
|
|
|
fn shr(self, rhs: usize) -> BigUint {
|
2015-01-20 19:17:41 +00:00
|
|
|
let n_unit = rhs / big_digit::BITS;
|
|
|
|
let n_bits = rhs % big_digit::BITS;
|
2015-11-16 18:56:30 +00:00
|
|
|
self.shr_unit(n_unit).shr_bits(n_bits)
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Zero for BigUint {
|
|
|
|
#[inline]
|
|
|
|
fn zero() -> BigUint { BigUint::new(Vec::new()) }
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn is_zero(&self) -> bool { self.data.is_empty() }
|
|
|
|
}
|
|
|
|
|
|
|
|
impl One for BigUint {
|
|
|
|
#[inline]
|
|
|
|
fn one() -> BigUint { BigUint::new(vec!(1)) }
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Unsigned for BigUint {}
|
|
|
|
|
2015-11-16 18:56:30 +00:00
|
|
|
forward_all_binop_to_val_ref_commutative!(impl Add for BigUint, add);
|
2014-12-16 14:38:35 +00:00
|
|
|
|
2015-12-10 21:33:28 +00:00
|
|
|
// Only for the Add impl:
|
|
|
|
#[must_use]
|
|
|
|
#[inline]
|
|
|
|
fn __add2(a: &mut [BigDigit], b: &[BigDigit]) -> BigDigit {
|
|
|
|
let mut b_iter = b.iter();
|
|
|
|
let mut carry = 0;
|
|
|
|
|
|
|
|
for ai in a.iter_mut() {
|
|
|
|
if let Some(bi) = b_iter.next() {
|
|
|
|
*ai = adc(*ai, *bi, &mut carry);
|
|
|
|
} else if carry != 0 {
|
|
|
|
*ai = adc(*ai, 0, &mut carry);
|
|
|
|
} else {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
debug_assert!(b_iter.next() == None);
|
|
|
|
carry
|
|
|
|
}
|
|
|
|
|
|
|
|
/// /Two argument addition of raw slices:
|
|
|
|
/// a += b
|
|
|
|
///
|
|
|
|
/// The caller _must_ ensure that a is big enough to store the result - typically this means
|
|
|
|
/// resizing a to max(a.len(), b.len()) + 1, to fit a possible carry.
|
|
|
|
fn add2(a: &mut [BigDigit], b: &[BigDigit]) {
|
|
|
|
let carry = __add2(a, b);
|
|
|
|
|
|
|
|
debug_assert!(carry == 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* We'd really prefer to avoid using add2/sub2 directly as much as possible - since they make the
|
|
|
|
* caller entirely responsible for ensuring a's vector is big enough, and that the result is
|
|
|
|
* normalized, they're rather error prone and verbose:
|
|
|
|
*
|
|
|
|
* We could implement the Add and Sub traits for BigUint + BigDigit slices, like below - this works
|
|
|
|
* great, except that then it becomes the module's public interface, which we probably don't want:
|
|
|
|
*
|
|
|
|
* I'm keeping the code commented out, because I think this is worth revisiting:
|
|
|
|
|
|
|
|
impl<'a> Add<&'a [BigDigit]> for BigUint {
|
2015-01-04 16:49:46 +00:00
|
|
|
type Output = BigUint;
|
|
|
|
|
2015-12-10 21:33:28 +00:00
|
|
|
fn add(mut self, other: &[BigDigit]) -> BigUint {
|
|
|
|
if self.data.len() < other.len() {
|
|
|
|
let extra = other.len() - self.data.len();
|
|
|
|
self.data.extend(repeat(0).take(extra));
|
|
|
|
}
|
2015-11-16 18:56:30 +00:00
|
|
|
|
2015-12-10 21:33:28 +00:00
|
|
|
let carry = __add2(&mut self.data[..], other);
|
|
|
|
if carry != 0 {
|
|
|
|
self.data.push(carry);
|
2015-11-16 18:56:30 +00:00
|
|
|
}
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2015-12-10 21:33:28 +00:00
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
*/
|
|
|
|
|
|
|
|
impl<'a> Add<&'a BigUint> for BigUint {
|
|
|
|
type Output = BigUint;
|
|
|
|
|
|
|
|
fn add(mut self, other: &BigUint) -> BigUint {
|
|
|
|
if self.data.len() < other.data.len() {
|
|
|
|
let extra = other.data.len() - self.data.len();
|
|
|
|
self.data.extend(repeat(0).take(extra));
|
2015-11-16 18:56:30 +00:00
|
|
|
}
|
|
|
|
|
2015-12-10 21:33:28 +00:00
|
|
|
let carry = __add2(&mut self.data[..], &other.data[..]);
|
|
|
|
if carry != 0 {
|
|
|
|
self.data.push(carry);
|
|
|
|
}
|
|
|
|
|
|
|
|
self
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-16 18:56:30 +00:00
|
|
|
forward_all_binop_to_val_ref!(impl Sub for BigUint, sub);
|
2014-12-16 14:38:35 +00:00
|
|
|
|
2015-12-10 21:33:28 +00:00
|
|
|
fn sub2(a: &mut [BigDigit], b: &[BigDigit]) {
|
|
|
|
let mut b_iter = b.iter();
|
|
|
|
let mut borrow = 0;
|
2015-01-04 16:49:46 +00:00
|
|
|
|
2015-12-10 21:33:28 +00:00
|
|
|
for ai in a.iter_mut() {
|
|
|
|
if let Some(bi) = b_iter.next() {
|
|
|
|
*ai = sbb(*ai, *bi, &mut borrow);
|
|
|
|
} else if borrow != 0 {
|
|
|
|
*ai = sbb(*ai, 0, &mut borrow);
|
|
|
|
} else {
|
|
|
|
break;
|
2015-11-16 18:56:30 +00:00
|
|
|
}
|
2015-12-10 21:33:28 +00:00
|
|
|
}
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2015-12-10 21:33:28 +00:00
|
|
|
/* note: we're _required_ to fail on underflow */
|
|
|
|
assert!(borrow == 0 && b_iter.all(|x| *x == 0),
|
|
|
|
"Cannot subtract b from a because b is larger than a.");
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> Sub<&'a BigUint> for BigUint {
|
|
|
|
type Output = BigUint;
|
2015-11-16 18:56:30 +00:00
|
|
|
|
2015-12-10 21:33:28 +00:00
|
|
|
fn sub(mut self, other: &BigUint) -> BigUint {
|
|
|
|
sub2(&mut self.data[..], &other.data[..]);
|
|
|
|
self.normalize()
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
Improve multiply performance
The main idea here is to do as much as possible with slices, instead of
allocating new BigUints (= heap allocations).
Current performance:
multiply_0: 10,507 ns/iter (+/- 987)
multiply_1: 2,788,734 ns/iter (+/- 100,079)
multiply_2: 69,923,515 ns/iter (+/- 4,550,902)
After this patch, we get:
multiply_0: 364 ns/iter (+/- 62)
multiply_1: 34,085 ns/iter (+/- 1,179)
multiply_2: 3,753,883 ns/iter (+/- 46,876)
2015-12-11 00:25:42 +00:00
|
|
|
fn sub_sign(a: &[BigDigit], b: &[BigDigit]) -> BigInt {
|
|
|
|
// Normalize:
|
|
|
|
let a = &a[..a.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)];
|
|
|
|
let b = &b[..b.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)];
|
2014-12-16 14:38:35 +00:00
|
|
|
|
Improve multiply performance
The main idea here is to do as much as possible with slices, instead of
allocating new BigUints (= heap allocations).
Current performance:
multiply_0: 10,507 ns/iter (+/- 987)
multiply_1: 2,788,734 ns/iter (+/- 100,079)
multiply_2: 69,923,515 ns/iter (+/- 4,550,902)
After this patch, we get:
multiply_0: 364 ns/iter (+/- 62)
multiply_1: 34,085 ns/iter (+/- 1,179)
multiply_2: 3,753,883 ns/iter (+/- 46,876)
2015-12-11 00:25:42 +00:00
|
|
|
match cmp_slice(a, b) {
|
|
|
|
Greater => {
|
|
|
|
let mut ret = BigUint::from_slice(a);
|
|
|
|
sub2(&mut ret.data[..], b);
|
|
|
|
BigInt::from_biguint(Plus, ret.normalize())
|
|
|
|
},
|
|
|
|
Less => {
|
|
|
|
let mut ret = BigUint::from_slice(b);
|
|
|
|
sub2(&mut ret.data[..], a);
|
|
|
|
BigInt::from_biguint(Minus, ret.normalize())
|
|
|
|
},
|
|
|
|
_ => Zero::zero(),
|
|
|
|
}
|
|
|
|
}
|
2014-12-16 14:38:35 +00:00
|
|
|
|
Improve multiply performance
The main idea here is to do as much as possible with slices, instead of
allocating new BigUints (= heap allocations).
Current performance:
multiply_0: 10,507 ns/iter (+/- 987)
multiply_1: 2,788,734 ns/iter (+/- 100,079)
multiply_2: 69,923,515 ns/iter (+/- 4,550,902)
After this patch, we get:
multiply_0: 364 ns/iter (+/- 62)
multiply_1: 34,085 ns/iter (+/- 1,179)
multiply_2: 3,753,883 ns/iter (+/- 46,876)
2015-12-11 00:25:42 +00:00
|
|
|
forward_all_binop_to_ref_ref!(impl Mul for BigUint, mul);
|
2015-01-04 16:49:46 +00:00
|
|
|
|
Improve multiply performance
The main idea here is to do as much as possible with slices, instead of
allocating new BigUints (= heap allocations).
Current performance:
multiply_0: 10,507 ns/iter (+/- 987)
multiply_1: 2,788,734 ns/iter (+/- 100,079)
multiply_2: 69,923,515 ns/iter (+/- 4,550,902)
After this patch, we get:
multiply_0: 364 ns/iter (+/- 62)
multiply_1: 34,085 ns/iter (+/- 1,179)
multiply_2: 3,753,883 ns/iter (+/- 46,876)
2015-12-11 00:25:42 +00:00
|
|
|
/// Three argument multiply accumulate:
|
|
|
|
/// acc += b * c
|
|
|
|
fn mac_digit(acc: &mut [BigDigit], b: &[BigDigit], c: BigDigit) {
|
|
|
|
if c == 0 { return; }
|
2014-09-16 17:35:35 +00:00
|
|
|
|
Improve multiply performance
The main idea here is to do as much as possible with slices, instead of
allocating new BigUints (= heap allocations).
Current performance:
multiply_0: 10,507 ns/iter (+/- 987)
multiply_1: 2,788,734 ns/iter (+/- 100,079)
multiply_2: 69,923,515 ns/iter (+/- 4,550,902)
After this patch, we get:
multiply_0: 364 ns/iter (+/- 62)
multiply_1: 34,085 ns/iter (+/- 1,179)
multiply_2: 3,753,883 ns/iter (+/- 46,876)
2015-12-11 00:25:42 +00:00
|
|
|
let mut b_iter = b.iter();
|
|
|
|
let mut carry = 0;
|
2014-09-16 17:35:35 +00:00
|
|
|
|
Improve multiply performance
The main idea here is to do as much as possible with slices, instead of
allocating new BigUints (= heap allocations).
Current performance:
multiply_0: 10,507 ns/iter (+/- 987)
multiply_1: 2,788,734 ns/iter (+/- 100,079)
multiply_2: 69,923,515 ns/iter (+/- 4,550,902)
After this patch, we get:
multiply_0: 364 ns/iter (+/- 62)
multiply_1: 34,085 ns/iter (+/- 1,179)
multiply_2: 3,753,883 ns/iter (+/- 46,876)
2015-12-11 00:25:42 +00:00
|
|
|
for ai in acc.iter_mut() {
|
|
|
|
if let Some(bi) = b_iter.next() {
|
|
|
|
*ai = mac_with_carry(*ai, *bi, c, &mut carry);
|
|
|
|
} else if carry != 0 {
|
|
|
|
*ai = mac_with_carry(*ai, 0, c, &mut carry);
|
|
|
|
} else {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
2014-09-16 17:35:35 +00:00
|
|
|
|
Improve multiply performance
The main idea here is to do as much as possible with slices, instead of
allocating new BigUints (= heap allocations).
Current performance:
multiply_0: 10,507 ns/iter (+/- 987)
multiply_1: 2,788,734 ns/iter (+/- 100,079)
multiply_2: 69,923,515 ns/iter (+/- 4,550,902)
After this patch, we get:
multiply_0: 364 ns/iter (+/- 62)
multiply_1: 34,085 ns/iter (+/- 1,179)
multiply_2: 3,753,883 ns/iter (+/- 46,876)
2015-12-11 00:25:42 +00:00
|
|
|
assert!(carry == 0);
|
|
|
|
}
|
2014-09-16 17:35:35 +00:00
|
|
|
|
Improve multiply performance
The main idea here is to do as much as possible with slices, instead of
allocating new BigUints (= heap allocations).
Current performance:
multiply_0: 10,507 ns/iter (+/- 987)
multiply_1: 2,788,734 ns/iter (+/- 100,079)
multiply_2: 69,923,515 ns/iter (+/- 4,550,902)
After this patch, we get:
multiply_0: 364 ns/iter (+/- 62)
multiply_1: 34,085 ns/iter (+/- 1,179)
multiply_2: 3,753,883 ns/iter (+/- 46,876)
2015-12-11 00:25:42 +00:00
|
|
|
/// Three argument multiply accumulate:
|
|
|
|
/// acc += b * c
|
|
|
|
fn mac3(acc: &mut [BigDigit], b: &[BigDigit], c: &[BigDigit]) {
|
|
|
|
let (x, y) = if b.len() < c.len() { (b, c) } else { (c, b) };
|
2014-09-16 17:35:35 +00:00
|
|
|
|
Improve multiply performance
The main idea here is to do as much as possible with slices, instead of
allocating new BigUints (= heap allocations).
Current performance:
multiply_0: 10,507 ns/iter (+/- 987)
multiply_1: 2,788,734 ns/iter (+/- 100,079)
multiply_2: 69,923,515 ns/iter (+/- 4,550,902)
After this patch, we get:
multiply_0: 364 ns/iter (+/- 62)
multiply_1: 34,085 ns/iter (+/- 1,179)
multiply_2: 3,753,883 ns/iter (+/- 46,876)
2015-12-11 00:25:42 +00:00
|
|
|
/*
|
|
|
|
* Karatsuba multiplication is slower than long multiplication for small x and y:
|
|
|
|
*/
|
|
|
|
if x.len() <= 4 {
|
|
|
|
for (i, xi) in x.iter().enumerate() {
|
|
|
|
mac_digit(&mut acc[i..], y, *xi);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
Improve multiply performance
The main idea here is to do as much as possible with slices, instead of
allocating new BigUints (= heap allocations).
Current performance:
multiply_0: 10,507 ns/iter (+/- 987)
multiply_1: 2,788,734 ns/iter (+/- 100,079)
multiply_2: 69,923,515 ns/iter (+/- 4,550,902)
After this patch, we get:
multiply_0: 364 ns/iter (+/- 62)
multiply_1: 34,085 ns/iter (+/- 1,179)
multiply_2: 3,753,883 ns/iter (+/- 46,876)
2015-12-11 00:25:42 +00:00
|
|
|
} else {
|
|
|
|
/*
|
|
|
|
* Karatsuba multiplication:
|
|
|
|
*
|
|
|
|
* The idea is that we break x and y up into two smaller numbers that each have about half
|
|
|
|
* as many digits, like so (note that multiplying by b is just a shift):
|
|
|
|
*
|
|
|
|
* x = x0 + x1 * b
|
|
|
|
* y = y0 + y1 * b
|
|
|
|
*
|
|
|
|
* With some algebra, we can compute x * y with three smaller products, where the inputs to
|
|
|
|
* each of the smaller products have only about half as many digits as x and y:
|
|
|
|
*
|
|
|
|
* x * y = (x0 + x1 * b) * (y0 + y1 * b)
|
|
|
|
*
|
|
|
|
* x * y = x0 * y0
|
|
|
|
* + x0 * y1 * b
|
|
|
|
* + x1 * y0 * b
|
|
|
|
* + x1 * y1 * b^2
|
|
|
|
*
|
|
|
|
* Let p0 = x0 * y0 and p2 = x1 * y1:
|
|
|
|
*
|
|
|
|
* x * y = p0
|
|
|
|
* + (x0 * y1 + x1 * p0) * b
|
|
|
|
* + p2 * b^2
|
|
|
|
*
|
|
|
|
* The real trick is that middle term:
|
|
|
|
*
|
|
|
|
* x0 * y1 + x1 * y0
|
|
|
|
*
|
|
|
|
* = x0 * y1 + x1 * y0 - p0 + p0 - p2 + p2
|
|
|
|
*
|
|
|
|
* = x0 * y1 + x1 * y0 - x0 * y0 - x1 * y1 + p0 + p2
|
|
|
|
*
|
|
|
|
* Now we complete the square:
|
|
|
|
*
|
|
|
|
* = -(x0 * y0 - x0 * y1 - x1 * y0 + x1 * y1) + p0 + p2
|
|
|
|
*
|
|
|
|
* = -((x1 - x0) * (y1 - y0)) + p0 + p2
|
|
|
|
*
|
|
|
|
* Let p1 = (x1 - x0) * (y1 - y0), and substitute back into our original formula:
|
|
|
|
*
|
|
|
|
* x * y = p0
|
|
|
|
* + (p0 + p2 - p1) * b
|
|
|
|
* + p2 * b^2
|
|
|
|
*
|
|
|
|
* Where the three intermediate products are:
|
|
|
|
*
|
|
|
|
* p0 = x0 * y0
|
|
|
|
* p1 = (x1 - x0) * (y1 - y0)
|
|
|
|
* p2 = x1 * y1
|
|
|
|
*
|
|
|
|
* In doing the computation, we take great care to avoid unnecessary temporary variables
|
|
|
|
* (since creating a BigUint requires a heap allocation): thus, we rearrange the formula a
|
|
|
|
* bit so we can use the same temporary variable for all the intermediate products:
|
|
|
|
*
|
|
|
|
* x * y = p2 * b^2 + p2 * b
|
|
|
|
* + p0 * b + p0
|
|
|
|
* - p1 * b
|
|
|
|
*
|
|
|
|
* The other trick we use is instead of doing explicit shifts, we slice acc at the
|
|
|
|
* appropriate offset when doing the add.
|
|
|
|
*/
|
|
|
|
|
|
|
|
/*
|
|
|
|
* When x is smaller than y, it's significantly faster to pick b such that x is split in
|
|
|
|
* half, not y:
|
|
|
|
*/
|
|
|
|
let b = x.len() / 2;
|
|
|
|
let (x0, x1) = x.split_at(b);
|
|
|
|
let (y0, y1) = y.split_at(b);
|
|
|
|
|
|
|
|
/* We reuse the same BigUint for all the intermediate multiplies: */
|
|
|
|
|
|
|
|
let len = y.len() + 1;
|
|
|
|
let mut p: BigUint = BigUint { data: Vec::with_capacity(len) };
|
|
|
|
p.data.extend(repeat(0).take(len));
|
|
|
|
|
|
|
|
// p2 = x1 * y1
|
|
|
|
mac3(&mut p.data[..], x1, y1);
|
|
|
|
|
|
|
|
// Not required, but the adds go faster if we drop any unneeded 0s from the end:
|
|
|
|
p = p.normalize();
|
|
|
|
|
|
|
|
add2(&mut acc[b..], &p.data[..]);
|
|
|
|
add2(&mut acc[b * 2..], &p.data[..]);
|
|
|
|
|
|
|
|
// Zero out p before the next multiply:
|
|
|
|
p.data.truncate(0);
|
|
|
|
p.data.extend(repeat(0).take(len));
|
|
|
|
|
|
|
|
// p0 = x0 * y0
|
|
|
|
mac3(&mut p.data[..], x0, y0);
|
|
|
|
p = p.normalize();
|
|
|
|
|
|
|
|
add2(&mut acc[..], &p.data[..]);
|
|
|
|
add2(&mut acc[b..], &p.data[..]);
|
|
|
|
|
|
|
|
// p1 = (x1 - x0) * (y1 - y0)
|
|
|
|
// We do this one last, since it may be negative and acc can't ever be negative:
|
|
|
|
let j0 = sub_sign(x1, x0);
|
|
|
|
let j1 = sub_sign(y1, y0);
|
|
|
|
|
|
|
|
match j0.sign * j1.sign {
|
|
|
|
Plus => {
|
|
|
|
p.data.truncate(0);
|
|
|
|
p.data.extend(repeat(0).take(len));
|
|
|
|
|
|
|
|
mac3(&mut p.data[..], &j0.data.data[..], &j1.data.data[..]);
|
|
|
|
p = p.normalize();
|
|
|
|
|
|
|
|
sub2(&mut acc[b..], &p.data[..]);
|
|
|
|
},
|
|
|
|
Minus => {
|
|
|
|
mac3(&mut acc[b..], &j0.data.data[..], &j1.data.data[..]);
|
|
|
|
},
|
|
|
|
NoSign => (),
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
Improve multiply performance
The main idea here is to do as much as possible with slices, instead of
allocating new BigUints (= heap allocations).
Current performance:
multiply_0: 10,507 ns/iter (+/- 987)
multiply_1: 2,788,734 ns/iter (+/- 100,079)
multiply_2: 69,923,515 ns/iter (+/- 4,550,902)
After this patch, we get:
multiply_0: 364 ns/iter (+/- 62)
multiply_1: 34,085 ns/iter (+/- 1,179)
multiply_2: 3,753,883 ns/iter (+/- 46,876)
2015-12-11 00:25:42 +00:00
|
|
|
fn mul3(x: &[BigDigit], y: &[BigDigit]) -> BigUint {
|
|
|
|
let len = x.len() + y.len() + 1;
|
|
|
|
let mut prod: BigUint = BigUint { data: Vec::with_capacity(len) };
|
|
|
|
|
|
|
|
// resize isn't stable yet:
|
|
|
|
//prod.data.resize(len, 0);
|
|
|
|
prod.data.extend(repeat(0).take(len));
|
|
|
|
|
|
|
|
mac3(&mut prod.data[..], x, y);
|
|
|
|
prod.normalize()
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, 'b> Mul<&'b BigUint> for &'a BigUint {
|
|
|
|
type Output = BigUint;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn mul(self, other: &BigUint) -> BigUint {
|
|
|
|
mul3(&self.data[..], &other.data[..])
|
|
|
|
}
|
|
|
|
}
|
2014-12-16 14:38:35 +00:00
|
|
|
|
2015-11-16 18:56:30 +00:00
|
|
|
forward_all_binop_to_ref_ref!(impl Div for BigUint, div);
|
2014-12-16 14:38:35 +00:00
|
|
|
|
2015-01-04 16:49:46 +00:00
|
|
|
impl<'a, 'b> Div<&'b BigUint> for &'a BigUint {
|
|
|
|
type Output = BigUint;
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[inline]
|
2014-12-16 14:38:35 +00:00
|
|
|
fn div(self, other: &BigUint) -> BigUint {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (q, _) = self.div_rem(other);
|
|
|
|
return q;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-16 18:56:30 +00:00
|
|
|
forward_all_binop_to_ref_ref!(impl Rem for BigUint, rem);
|
2014-12-16 14:38:35 +00:00
|
|
|
|
2015-01-04 16:49:46 +00:00
|
|
|
impl<'a, 'b> Rem<&'b BigUint> for &'a BigUint {
|
|
|
|
type Output = BigUint;
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[inline]
|
2014-12-16 14:38:35 +00:00
|
|
|
fn rem(self, other: &BigUint) -> BigUint {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (_, r) = self.div_rem(other);
|
|
|
|
return r;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-04 16:49:46 +00:00
|
|
|
impl Neg for BigUint {
|
|
|
|
type Output = BigUint;
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[inline]
|
2014-12-21 10:41:03 +00:00
|
|
|
fn neg(self) -> BigUint { panic!() }
|
|
|
|
}
|
|
|
|
|
2015-01-04 16:49:46 +00:00
|
|
|
impl<'a> Neg for &'a BigUint {
|
|
|
|
type Output = BigUint;
|
|
|
|
|
2014-12-21 10:41:03 +00:00
|
|
|
#[inline]
|
|
|
|
fn neg(self) -> BigUint { panic!() }
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl CheckedAdd for BigUint {
|
|
|
|
#[inline]
|
|
|
|
fn checked_add(&self, v: &BigUint) -> Option<BigUint> {
|
|
|
|
return Some(self.add(v));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl CheckedSub for BigUint {
|
|
|
|
#[inline]
|
|
|
|
fn checked_sub(&self, v: &BigUint) -> Option<BigUint> {
|
|
|
|
if *self < *v {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
return Some(self.sub(v));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl CheckedMul for BigUint {
|
|
|
|
#[inline]
|
|
|
|
fn checked_mul(&self, v: &BigUint) -> Option<BigUint> {
|
|
|
|
return Some(self.mul(v));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl CheckedDiv for BigUint {
|
|
|
|
#[inline]
|
|
|
|
fn checked_div(&self, v: &BigUint) -> Option<BigUint> {
|
|
|
|
if v.is_zero() {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
return Some(self.div(v));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Integer for BigUint {
|
|
|
|
#[inline]
|
|
|
|
fn div_rem(&self, other: &BigUint) -> (BigUint, BigUint) {
|
|
|
|
self.div_mod_floor(other)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn div_floor(&self, other: &BigUint) -> BigUint {
|
|
|
|
let (d, _) = self.div_mod_floor(other);
|
|
|
|
return d;
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn mod_floor(&self, other: &BigUint) -> BigUint {
|
|
|
|
let (_, m) = self.div_mod_floor(other);
|
|
|
|
return m;
|
|
|
|
}
|
|
|
|
|
|
|
|
fn div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint) {
|
2014-10-30 13:20:15 +00:00
|
|
|
if other.is_zero() { panic!() }
|
2014-09-16 17:35:35 +00:00
|
|
|
if self.is_zero() { return (Zero::zero(), Zero::zero()); }
|
2015-11-16 18:56:30 +00:00
|
|
|
if *other == One::one() { return (self.clone(), Zero::zero()); }
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
match self.cmp(other) {
|
2015-11-16 18:56:30 +00:00
|
|
|
Less => return (Zero::zero(), self.clone()),
|
2014-09-16 17:35:35 +00:00
|
|
|
Equal => return (One::one(), Zero::zero()),
|
|
|
|
Greater => {} // Do nothing
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut shift = 0;
|
|
|
|
let mut n = *other.data.last().unwrap();
|
2015-01-20 19:17:41 +00:00
|
|
|
while n < (1 << big_digit::BITS - 2) {
|
2014-09-16 17:35:35 +00:00
|
|
|
n <<= 1;
|
|
|
|
shift += 1;
|
|
|
|
}
|
2015-01-20 19:17:41 +00:00
|
|
|
assert!(shift < big_digit::BITS);
|
2014-12-16 14:38:35 +00:00
|
|
|
let (d, m) = div_mod_floor_inner(self << shift, other << shift);
|
2014-09-16 17:35:35 +00:00
|
|
|
return (d, m >> shift);
|
|
|
|
|
|
|
|
|
|
|
|
fn div_mod_floor_inner(a: BigUint, b: BigUint) -> (BigUint, BigUint) {
|
|
|
|
let mut m = a;
|
|
|
|
let mut d: BigUint = Zero::zero();
|
|
|
|
let mut n = 1;
|
|
|
|
while m >= b {
|
|
|
|
let (d0, d_unit, b_unit) = div_estimate(&m, &b, n);
|
|
|
|
let mut d0 = d0;
|
2014-12-16 14:38:35 +00:00
|
|
|
let mut prod = &b * &d0;
|
2014-09-16 17:35:35 +00:00
|
|
|
while prod > m {
|
|
|
|
// FIXME(#5992): assignment operator overloads
|
2014-12-16 14:38:35 +00:00
|
|
|
// d0 -= &d_unit
|
|
|
|
d0 = d0 - &d_unit;
|
2014-09-16 17:35:35 +00:00
|
|
|
// FIXME(#5992): assignment operator overloads
|
2014-12-16 14:38:35 +00:00
|
|
|
// prod -= &b_unit;
|
|
|
|
prod = prod - &b_unit
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
if d0.is_zero() {
|
|
|
|
n = 2;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
n = 1;
|
|
|
|
// FIXME(#5992): assignment operator overloads
|
|
|
|
// d += d0;
|
|
|
|
d = d + d0;
|
|
|
|
// FIXME(#5992): assignment operator overloads
|
|
|
|
// m -= prod;
|
|
|
|
m = m - prod;
|
|
|
|
}
|
|
|
|
return (d, m);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2015-01-09 11:36:03 +00:00
|
|
|
fn div_estimate(a: &BigUint, b: &BigUint, n: usize)
|
2015-04-03 06:29:17 +00:00
|
|
|
-> (BigUint, BigUint, BigUint) {
|
|
|
|
if a.data.len() < n {
|
|
|
|
return (Zero::zero(), Zero::zero(), (*a).clone());
|
|
|
|
}
|
|
|
|
|
|
|
|
let an = &a.data[a.data.len() - n ..];
|
|
|
|
let bn = *b.data.last().unwrap();
|
|
|
|
let mut d = Vec::with_capacity(an.len());
|
|
|
|
let mut carry = 0;
|
|
|
|
for elt in an.iter().rev() {
|
|
|
|
let ai = big_digit::to_doublebigdigit(carry, *elt);
|
|
|
|
let di = ai / (bn as DoubleBigDigit);
|
|
|
|
assert!(di < big_digit::BASE);
|
|
|
|
carry = (ai % (bn as DoubleBigDigit)) as BigDigit;
|
|
|
|
d.push(di as BigDigit)
|
|
|
|
}
|
|
|
|
d.reverse();
|
|
|
|
|
|
|
|
let shift = (a.data.len() - an.len()) - (b.data.len() - 1);
|
|
|
|
if shift == 0 {
|
|
|
|
return (BigUint::new(d), One::one(), (*b).clone());
|
|
|
|
}
|
|
|
|
let one: BigUint = One::one();
|
|
|
|
return (BigUint::new(d).shl_unit(shift),
|
|
|
|
one.shl_unit(shift),
|
|
|
|
b.shl_unit(shift));
|
|
|
|
}
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
|
|
|
|
///
|
|
|
|
/// The result is always positive.
|
|
|
|
#[inline]
|
|
|
|
fn gcd(&self, other: &BigUint) -> BigUint {
|
|
|
|
// Use Euclid's algorithm
|
|
|
|
let mut m = (*self).clone();
|
|
|
|
let mut n = (*other).clone();
|
|
|
|
while !m.is_zero() {
|
|
|
|
let temp = m;
|
2014-12-16 14:38:35 +00:00
|
|
|
m = n % &temp;
|
2014-09-16 17:35:35 +00:00
|
|
|
n = temp;
|
|
|
|
}
|
|
|
|
return n;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
|
|
|
|
#[inline]
|
2014-12-16 14:38:35 +00:00
|
|
|
fn lcm(&self, other: &BigUint) -> BigUint { ((self * other) / self.gcd(other)) }
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
/// Deprecated, use `is_multiple_of` instead.
|
|
|
|
#[inline]
|
2014-12-16 14:38:35 +00:00
|
|
|
fn divides(&self, other: &BigUint) -> bool { self.is_multiple_of(other) }
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
/// Returns `true` if the number is a multiple of `other`.
|
|
|
|
#[inline]
|
2014-12-16 14:38:35 +00:00
|
|
|
fn is_multiple_of(&self, other: &BigUint) -> bool { (self % other).is_zero() }
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
/// Returns `true` if the number is divisible by `2`.
|
|
|
|
#[inline]
|
|
|
|
fn is_even(&self) -> bool {
|
|
|
|
// Considering only the last digit.
|
2015-01-01 17:07:52 +00:00
|
|
|
match self.data.first() {
|
2014-09-16 17:35:35 +00:00
|
|
|
Some(x) => x.is_even(),
|
|
|
|
None => true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns `true` if the number is not divisible by `2`.
|
|
|
|
#[inline]
|
|
|
|
fn is_odd(&self) -> bool { !self.is_even() }
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ToPrimitive for BigUint {
|
|
|
|
#[inline]
|
|
|
|
fn to_i64(&self) -> Option<i64> {
|
|
|
|
self.to_u64().and_then(|n| {
|
|
|
|
// If top bit of u64 is set, it's too large to convert to i64.
|
|
|
|
if n >> 63 == 0 {
|
|
|
|
Some(n as i64)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// `DoubleBigDigit` size dependent
|
|
|
|
#[inline]
|
|
|
|
fn to_u64(&self) -> Option<u64> {
|
|
|
|
match self.data.len() {
|
|
|
|
0 => Some(0),
|
2014-11-04 14:22:21 +00:00
|
|
|
1 => Some(self.data[0] as u64),
|
2015-01-20 19:17:41 +00:00
|
|
|
2 => Some(big_digit::to_doublebigdigit(self.data[1], self.data[0])
|
2014-09-16 17:35:35 +00:00
|
|
|
as u64),
|
|
|
|
_ => None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl FromPrimitive for BigUint {
|
|
|
|
#[inline]
|
|
|
|
fn from_i64(n: i64) -> Option<BigUint> {
|
|
|
|
if n > 0 {
|
|
|
|
FromPrimitive::from_u64(n as u64)
|
|
|
|
} else if n == 0 {
|
|
|
|
Some(Zero::zero())
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// `DoubleBigDigit` size dependent
|
|
|
|
#[inline]
|
|
|
|
fn from_u64(n: u64) -> Option<BigUint> {
|
2015-01-20 19:17:41 +00:00
|
|
|
let n = match big_digit::from_doublebigdigit(n) {
|
2014-09-16 17:35:35 +00:00
|
|
|
(0, 0) => Zero::zero(),
|
|
|
|
(0, n0) => BigUint::new(vec!(n0)),
|
|
|
|
(n1, n0) => BigUint::new(vec!(n0, n1))
|
|
|
|
};
|
|
|
|
Some(n)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A generic trait for converting a value to a `BigUint`.
|
|
|
|
pub trait ToBigUint {
|
|
|
|
/// Converts the value of `self` to a `BigUint`.
|
2015-01-09 21:54:32 +00:00
|
|
|
fn to_biguint(&self) -> Option<BigUint>;
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl ToBigUint for BigInt {
|
|
|
|
#[inline]
|
2015-01-09 21:54:32 +00:00
|
|
|
fn to_biguint(&self) -> Option<BigUint> {
|
2014-09-16 17:35:35 +00:00
|
|
|
if self.sign == Plus {
|
|
|
|
Some(self.data.clone())
|
2014-09-21 00:58:59 +00:00
|
|
|
} else if self.sign == NoSign {
|
2014-09-16 17:35:35 +00:00
|
|
|
Some(Zero::zero())
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ToBigUint for BigUint {
|
|
|
|
#[inline]
|
2015-01-09 21:54:32 +00:00
|
|
|
fn to_biguint(&self) -> Option<BigUint> {
|
2014-09-16 17:35:35 +00:00
|
|
|
Some(self.clone())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-09 21:54:32 +00:00
|
|
|
macro_rules! impl_to_biguint {
|
2014-09-16 17:35:35 +00:00
|
|
|
($T:ty, $from_ty:path) => {
|
|
|
|
impl ToBigUint for $T {
|
|
|
|
#[inline]
|
2015-01-09 21:54:32 +00:00
|
|
|
fn to_biguint(&self) -> Option<BigUint> {
|
2014-09-16 17:35:35 +00:00
|
|
|
$from_ty(*self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2014-12-19 02:01:24 +00:00
|
|
|
}
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2015-03-04 17:45:19 +00:00
|
|
|
impl_to_biguint!(isize, FromPrimitive::from_isize);
|
2015-01-09 21:54:32 +00:00
|
|
|
impl_to_biguint!(i8, FromPrimitive::from_i8);
|
|
|
|
impl_to_biguint!(i16, FromPrimitive::from_i16);
|
|
|
|
impl_to_biguint!(i32, FromPrimitive::from_i32);
|
|
|
|
impl_to_biguint!(i64, FromPrimitive::from_i64);
|
2015-03-04 17:45:19 +00:00
|
|
|
impl_to_biguint!(usize, FromPrimitive::from_usize);
|
2015-01-09 21:54:32 +00:00
|
|
|
impl_to_biguint!(u8, FromPrimitive::from_u8);
|
|
|
|
impl_to_biguint!(u16, FromPrimitive::from_u16);
|
|
|
|
impl_to_biguint!(u32, FromPrimitive::from_u32);
|
|
|
|
impl_to_biguint!(u64, FromPrimitive::from_u64);
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2015-11-09 20:50:25 +00:00
|
|
|
fn to_str_radix_reversed(u: &BigUint, radix: u32) -> Vec<u8> {
|
|
|
|
if radix < 2 || radix > 36 {
|
|
|
|
panic!("invalid radix: {}", radix);
|
|
|
|
}
|
|
|
|
|
|
|
|
if u.is_zero() {
|
|
|
|
vec![b'0']
|
|
|
|
} else {
|
|
|
|
let mut res = Vec::new();
|
|
|
|
let mut digits = u.data.to_vec();
|
2015-04-03 06:29:17 +00:00
|
|
|
|
2015-11-16 18:20:42 +00:00
|
|
|
while !digits.is_empty() {
|
|
|
|
let rem = div_rem_in_place(&mut digits, radix);
|
2015-11-09 20:50:25 +00:00
|
|
|
res.push(to_digit(rem as u8));
|
2015-11-16 18:20:42 +00:00
|
|
|
|
|
|
|
// If we finished the most significant digit, drop it
|
|
|
|
if let Some(&0) = digits.last() {
|
|
|
|
digits.pop();
|
|
|
|
}
|
2015-04-03 06:29:17 +00:00
|
|
|
}
|
2015-11-09 20:50:25 +00:00
|
|
|
|
|
|
|
res
|
2015-04-03 06:29:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-09 20:50:25 +00:00
|
|
|
fn div_rem_in_place(digits: &mut [BigDigit], divisor: BigDigit) -> BigDigit {
|
|
|
|
let mut rem = 0;
|
|
|
|
|
|
|
|
for d in digits.iter_mut().rev() {
|
|
|
|
let (q, r) = full_div_rem(*d, divisor, rem);
|
|
|
|
*d = q;
|
|
|
|
rem = r;
|
2015-04-03 06:29:17 +00:00
|
|
|
}
|
2015-11-09 20:50:25 +00:00
|
|
|
|
|
|
|
rem
|
2015-04-03 06:29:17 +00:00
|
|
|
}
|
|
|
|
|
2015-11-09 20:50:25 +00:00
|
|
|
fn full_div_rem(a: BigDigit, b: BigDigit, borrow: BigDigit) -> (BigDigit, BigDigit) {
|
|
|
|
let lo = a as DoubleBigDigit;
|
|
|
|
let hi = borrow as DoubleBigDigit;
|
|
|
|
|
|
|
|
let lhs = lo | (hi << big_digit::BITS);
|
|
|
|
let rhs = b as DoubleBigDigit;
|
|
|
|
((lhs / rhs) as BigDigit, (lhs % rhs) as BigDigit)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn to_digit(b: u8) -> u8 {
|
|
|
|
match b {
|
|
|
|
0 ... 9 => b'0' + b,
|
|
|
|
10 ... 35 => b'a' - 10 + b,
|
|
|
|
_ => panic!("invalid digit: {}", b)
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-11-04 14:20:37 +00:00
|
|
|
impl BigUint {
|
|
|
|
/// Creates and initializes a `BigUint`.
|
|
|
|
///
|
2015-01-20 23:52:18 +00:00
|
|
|
/// The digits are in little-endian base 2^32.
|
2014-11-04 14:20:37 +00:00
|
|
|
#[inline]
|
2015-12-10 21:33:28 +00:00
|
|
|
pub fn new(digits: Vec<BigDigit>) -> BigUint {
|
|
|
|
BigUint { data: digits }.normalize()
|
2014-11-04 14:20:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Creates and initializes a `BigUint`.
|
|
|
|
///
|
2015-01-20 23:52:18 +00:00
|
|
|
/// The digits are in little-endian base 2^32.
|
2014-11-04 14:20:37 +00:00
|
|
|
#[inline]
|
|
|
|
pub fn from_slice(slice: &[BigDigit]) -> BigUint {
|
|
|
|
BigUint::new(slice.to_vec())
|
|
|
|
}
|
|
|
|
|
2015-01-21 01:38:51 +00:00
|
|
|
/// Creates and initializes a `BigUint`.
|
|
|
|
///
|
|
|
|
/// The bytes are in big-endian byte order.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use num::bigint::BigUint;
|
|
|
|
///
|
2015-04-15 19:43:37 +00:00
|
|
|
/// assert_eq!(BigUint::from_bytes_be(b"A"),
|
|
|
|
/// BigUint::parse_bytes(b"65", 10).unwrap());
|
|
|
|
/// assert_eq!(BigUint::from_bytes_be(b"AA"),
|
|
|
|
/// BigUint::parse_bytes(b"16705", 10).unwrap());
|
|
|
|
/// assert_eq!(BigUint::from_bytes_be(b"AB"),
|
|
|
|
/// BigUint::parse_bytes(b"16706", 10).unwrap());
|
|
|
|
/// assert_eq!(BigUint::from_bytes_be(b"Hello world!"),
|
|
|
|
/// BigUint::parse_bytes(b"22405534230753963835153736737", 10).unwrap());
|
2015-01-21 01:38:51 +00:00
|
|
|
/// ```
|
|
|
|
#[inline]
|
|
|
|
pub fn from_bytes_be(bytes: &[u8]) -> BigUint {
|
|
|
|
if bytes.is_empty() {
|
|
|
|
Zero::zero()
|
|
|
|
} else {
|
|
|
|
BigUint::parse_bytes(bytes.to_hex().as_bytes(), 16).unwrap()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Creates and initializes a `BigUint`.
|
|
|
|
///
|
|
|
|
/// The bytes are in little-endian byte order.
|
|
|
|
#[inline]
|
|
|
|
pub fn from_bytes_le(bytes: &[u8]) -> BigUint {
|
|
|
|
let mut v = bytes.to_vec();
|
|
|
|
v.reverse();
|
|
|
|
BigUint::from_bytes_be(&*v)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the byte representation of the `BigUint` in little-endian byte order.
|
2015-04-15 19:43:37 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use num::bigint::BigUint;
|
|
|
|
///
|
|
|
|
/// let i = BigUint::parse_bytes(b"1125", 10).unwrap();
|
|
|
|
/// assert_eq!(i.to_bytes_le(), vec![101, 4]);
|
|
|
|
/// ```
|
2015-01-21 01:38:51 +00:00
|
|
|
#[inline]
|
|
|
|
pub fn to_bytes_le(&self) -> Vec<u8> {
|
|
|
|
let mut result = Vec::new();
|
|
|
|
for word in self.data.iter() {
|
|
|
|
let mut w = *word;
|
|
|
|
for _ in 0..mem::size_of::<BigDigit>() {
|
|
|
|
let b = (w & 0xFF) as u8;
|
|
|
|
w = w >> 8;
|
|
|
|
result.push(b);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-16 18:20:42 +00:00
|
|
|
while let Some(&0) = result.last() {
|
|
|
|
result.pop();
|
2015-01-21 01:38:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if result.is_empty() {
|
|
|
|
vec![0]
|
|
|
|
} else {
|
|
|
|
result
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the byte representation of the `BigUint` in big-endian byte order.
|
2015-04-15 19:43:37 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use num::bigint::BigUint;
|
|
|
|
///
|
|
|
|
/// let i = BigUint::parse_bytes(b"1125", 10).unwrap();
|
|
|
|
/// assert_eq!(i.to_bytes_be(), vec![4, 101]);
|
|
|
|
/// ```
|
2015-01-21 01:38:51 +00:00
|
|
|
#[inline]
|
|
|
|
pub fn to_bytes_be(&self) -> Vec<u8> {
|
|
|
|
let mut v = self.to_bytes_le();
|
|
|
|
v.reverse();
|
|
|
|
v
|
|
|
|
}
|
|
|
|
|
2015-11-09 20:50:25 +00:00
|
|
|
/// Returns the integer formatted as a string in the given radix.
|
|
|
|
/// `radix` must be in the range `[2, 36]`.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use num::bigint::BigUint;
|
|
|
|
///
|
|
|
|
/// let i = BigUint::parse_bytes(b"ff", 16).unwrap();
|
|
|
|
/// assert_eq!(i.to_str_radix(16), "ff");
|
|
|
|
/// ```
|
|
|
|
#[inline]
|
|
|
|
pub fn to_str_radix(&self, radix: u32) -> String {
|
|
|
|
let mut v = to_str_radix_reversed(self, radix);
|
|
|
|
v.reverse();
|
|
|
|
unsafe { String::from_utf8_unchecked(v) }
|
|
|
|
}
|
|
|
|
|
2014-11-04 14:20:37 +00:00
|
|
|
/// Creates and initializes a `BigUint`.
|
2015-01-20 23:52:18 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use num::bigint::{BigUint, ToBigUint};
|
|
|
|
///
|
2015-04-15 19:43:37 +00:00
|
|
|
/// assert_eq!(BigUint::parse_bytes(b"1234", 10), ToBigUint::to_biguint(&1234));
|
|
|
|
/// assert_eq!(BigUint::parse_bytes(b"ABCD", 16), ToBigUint::to_biguint(&0xABCD));
|
|
|
|
/// assert_eq!(BigUint::parse_bytes(b"G", 16), None);
|
2015-01-20 23:52:18 +00:00
|
|
|
/// ```
|
2014-11-04 14:20:37 +00:00
|
|
|
#[inline]
|
2015-02-19 00:29:46 +00:00
|
|
|
pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigUint> {
|
2015-04-03 06:29:17 +00:00
|
|
|
str::from_utf8(buf).ok().and_then(|s| BigUint::from_str_radix(s, radix).ok())
|
2014-11-04 14:20:37 +00:00
|
|
|
}
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
#[inline]
|
2015-01-09 11:36:03 +00:00
|
|
|
fn shl_unit(&self, n_unit: usize) -> BigUint {
|
2015-11-16 18:56:30 +00:00
|
|
|
if n_unit == 0 || self.is_zero() { return self.clone(); }
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2015-11-16 18:56:30 +00:00
|
|
|
let mut v = vec![0; n_unit];
|
2015-04-03 06:29:17 +00:00
|
|
|
v.extend(self.data.iter().cloned());
|
2014-10-21 16:27:08 +00:00
|
|
|
BigUint::new(v)
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
2015-11-16 18:56:30 +00:00
|
|
|
fn shl_bits(self, n_bits: usize) -> BigUint {
|
|
|
|
if n_bits == 0 || self.is_zero() { return self; }
|
|
|
|
|
|
|
|
assert!(n_bits < big_digit::BITS);
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
let mut carry = 0;
|
2015-11-16 18:56:30 +00:00
|
|
|
let mut shifted = self.data;
|
|
|
|
for elem in shifted.iter_mut() {
|
|
|
|
let new_carry = *elem >> (big_digit::BITS - n_bits);
|
|
|
|
*elem = (*elem << n_bits) | carry;
|
|
|
|
carry = new_carry;
|
|
|
|
}
|
|
|
|
if carry != 0 {
|
|
|
|
shifted.push(carry);
|
|
|
|
}
|
|
|
|
BigUint::new(shifted)
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
2015-01-09 11:36:03 +00:00
|
|
|
fn shr_unit(&self, n_unit: usize) -> BigUint {
|
2015-11-16 18:56:30 +00:00
|
|
|
if n_unit == 0 { return self.clone(); }
|
2014-09-16 17:35:35 +00:00
|
|
|
if self.data.len() < n_unit { return Zero::zero(); }
|
2015-01-09 11:36:03 +00:00
|
|
|
BigUint::from_slice(&self.data[n_unit ..])
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
2015-11-16 18:56:30 +00:00
|
|
|
fn shr_bits(self, n_bits: usize) -> BigUint {
|
|
|
|
if n_bits == 0 || self.data.is_empty() { return self; }
|
|
|
|
|
|
|
|
assert!(n_bits < big_digit::BITS);
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
let mut borrow = 0;
|
2015-11-16 18:56:30 +00:00
|
|
|
let mut shifted = self.data;
|
|
|
|
for elem in shifted.iter_mut().rev() {
|
|
|
|
let new_borrow = *elem << (big_digit::BITS - n_bits);
|
|
|
|
*elem = (*elem >> n_bits) | borrow;
|
|
|
|
borrow = new_borrow;
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
2015-11-16 18:56:30 +00:00
|
|
|
BigUint::new(shifted)
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Determines the fewest bits necessary to express the `BigUint`.
|
2015-01-09 11:36:03 +00:00
|
|
|
pub fn bits(&self) -> usize {
|
2014-09-16 17:35:35 +00:00
|
|
|
if self.is_zero() { return 0; }
|
|
|
|
let zeros = self.data.last().unwrap().leading_zeros();
|
2015-03-04 16:43:44 +00:00
|
|
|
return self.data.len()*big_digit::BITS - zeros as usize;
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
2015-12-10 21:33:28 +00:00
|
|
|
|
|
|
|
/// Strips off trailing zero bigdigits - comparisons require the last element in the vector to
|
|
|
|
/// be nonzero.
|
|
|
|
#[inline]
|
|
|
|
fn normalize(mut self) -> BigUint {
|
|
|
|
while let Some(&0) = self.data.last() {
|
|
|
|
self.data.pop();
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// `DoubleBigDigit` size dependent
|
|
|
|
#[inline]
|
2015-02-19 00:29:46 +00:00
|
|
|
fn get_radix_base(radix: u32) -> (DoubleBigDigit, usize) {
|
2014-09-16 17:35:35 +00:00
|
|
|
match radix {
|
|
|
|
2 => (4294967296, 32),
|
|
|
|
3 => (3486784401, 20),
|
|
|
|
4 => (4294967296, 16),
|
|
|
|
5 => (1220703125, 13),
|
|
|
|
6 => (2176782336, 12),
|
|
|
|
7 => (1977326743, 11),
|
|
|
|
8 => (1073741824, 10),
|
|
|
|
9 => (3486784401, 10),
|
|
|
|
10 => (1000000000, 9),
|
|
|
|
11 => (2357947691, 9),
|
|
|
|
12 => (429981696, 8),
|
|
|
|
13 => (815730721, 8),
|
|
|
|
14 => (1475789056, 8),
|
|
|
|
15 => (2562890625, 8),
|
|
|
|
16 => (4294967296, 8),
|
2014-10-30 13:20:15 +00:00
|
|
|
_ => panic!("The radix must be within (1, 16]")
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A Sign is a `BigInt`'s composing element.
|
2015-02-03 19:05:55 +00:00
|
|
|
#[derive(PartialEq, PartialOrd, Eq, Ord, Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
|
2014-09-21 00:58:59 +00:00
|
|
|
pub enum Sign { Minus, NoSign, Plus }
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2015-01-04 16:49:46 +00:00
|
|
|
impl Neg for Sign {
|
|
|
|
type Output = Sign;
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
/// Negate Sign value.
|
|
|
|
#[inline]
|
2014-12-21 10:41:03 +00:00
|
|
|
fn neg(self) -> Sign {
|
|
|
|
match self {
|
|
|
|
Minus => Plus,
|
|
|
|
NoSign => NoSign,
|
|
|
|
Plus => Minus
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-16 19:04:41 +00:00
|
|
|
impl Mul<Sign> for Sign {
|
|
|
|
type Output = Sign;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn mul(self, other: Sign) -> Sign {
|
|
|
|
match (self, other) {
|
|
|
|
(NoSign, _) | (_, NoSign) => NoSign,
|
|
|
|
(Plus, Plus) | (Minus, Minus) => Plus,
|
|
|
|
(Plus, Minus) | (Minus, Plus) => Minus,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
/// A big signed integer type.
|
2015-01-23 16:54:55 +00:00
|
|
|
#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
|
2014-09-16 17:35:35 +00:00
|
|
|
pub struct BigInt {
|
|
|
|
sign: Sign,
|
|
|
|
data: BigUint
|
|
|
|
}
|
|
|
|
|
|
|
|
impl PartialEq for BigInt {
|
|
|
|
#[inline]
|
|
|
|
fn eq(&self, other: &BigInt) -> bool {
|
|
|
|
self.cmp(other) == Equal
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Eq for BigInt {}
|
|
|
|
|
|
|
|
impl PartialOrd for BigInt {
|
|
|
|
#[inline]
|
|
|
|
fn partial_cmp(&self, other: &BigInt) -> Option<Ordering> {
|
|
|
|
Some(self.cmp(other))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Ord for BigInt {
|
|
|
|
#[inline]
|
|
|
|
fn cmp(&self, other: &BigInt) -> Ordering {
|
|
|
|
let scmp = self.sign.cmp(&other.sign);
|
|
|
|
if scmp != Equal { return scmp; }
|
|
|
|
|
|
|
|
match self.sign {
|
2014-09-21 00:58:59 +00:00
|
|
|
NoSign => Equal,
|
2014-09-16 17:35:35 +00:00
|
|
|
Plus => self.data.cmp(&other.data),
|
|
|
|
Minus => other.data.cmp(&self.data),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for BigInt {
|
|
|
|
#[inline]
|
|
|
|
fn default() -> BigInt { Zero::zero() }
|
|
|
|
}
|
|
|
|
|
2015-01-23 16:54:55 +00:00
|
|
|
impl fmt::Display for BigInt {
|
2015-01-09 11:36:03 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
2015-11-09 20:50:25 +00:00
|
|
|
write!(f, "{}", self.to_str_radix(10))
|
2015-01-09 11:36:03 +00:00
|
|
|
}
|
|
|
|
}
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2015-02-20 18:26:13 +00:00
|
|
|
impl hash::Hash for BigInt {
|
|
|
|
fn hash<H>(&self, state: &mut H) where H: hash::Hasher {
|
2014-09-16 17:35:35 +00:00
|
|
|
(self.sign == Plus).hash(state);
|
|
|
|
self.data.hash(state);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl FromStr for BigInt {
|
2015-02-03 19:42:46 +00:00
|
|
|
type Err = ParseBigIntError;
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[inline]
|
2015-02-03 19:42:46 +00:00
|
|
|
fn from_str(s: &str) -> Result<BigInt, ParseBigIntError> {
|
2015-04-03 06:29:17 +00:00
|
|
|
BigInt::from_str_radix(s, 10)
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-04-03 06:29:17 +00:00
|
|
|
impl Num for BigInt {
|
|
|
|
type FromStrRadixErr = ParseBigIntError;
|
|
|
|
|
|
|
|
/// Creates and initializes a BigInt.
|
|
|
|
#[inline]
|
|
|
|
fn from_str_radix(s: &str, radix: u32) -> Result<BigInt, ParseBigIntError> {
|
|
|
|
if s.is_empty() { return Err(ParseBigIntError::Other); }
|
|
|
|
let mut sign = Plus;
|
|
|
|
let mut start = 0;
|
|
|
|
if s.starts_with("-") {
|
|
|
|
sign = Minus;
|
|
|
|
start = 1;
|
|
|
|
}
|
|
|
|
BigUint::from_str_radix(&s[start ..], radix)
|
|
|
|
.map(|bu| BigInt::from_biguint(sign, bu))
|
|
|
|
}
|
|
|
|
}
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2015-01-09 11:36:03 +00:00
|
|
|
impl Shl<usize> for BigInt {
|
2015-01-04 16:49:46 +00:00
|
|
|
type Output = BigInt;
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[inline]
|
2015-01-09 11:36:03 +00:00
|
|
|
fn shl(self, rhs: usize) -> BigInt { (&self) << rhs }
|
2014-12-16 14:38:35 +00:00
|
|
|
}
|
|
|
|
|
2015-01-09 11:36:03 +00:00
|
|
|
impl<'a> Shl<usize> for &'a BigInt {
|
2015-01-04 16:49:46 +00:00
|
|
|
type Output = BigInt;
|
|
|
|
|
2014-12-16 14:38:35 +00:00
|
|
|
#[inline]
|
2015-01-09 11:36:03 +00:00
|
|
|
fn shl(self, rhs: usize) -> BigInt {
|
2014-12-16 14:38:35 +00:00
|
|
|
BigInt::from_biguint(self.sign, &self.data << rhs)
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-09 11:36:03 +00:00
|
|
|
impl Shr<usize> for BigInt {
|
2015-01-04 16:49:46 +00:00
|
|
|
type Output = BigInt;
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[inline]
|
2015-01-09 11:36:03 +00:00
|
|
|
fn shr(self, rhs: usize) -> BigInt { (&self) >> rhs }
|
2014-12-16 14:38:35 +00:00
|
|
|
}
|
|
|
|
|
2015-01-09 11:36:03 +00:00
|
|
|
impl<'a> Shr<usize> for &'a BigInt {
|
2015-01-04 16:49:46 +00:00
|
|
|
type Output = BigInt;
|
|
|
|
|
2014-12-16 14:38:35 +00:00
|
|
|
#[inline]
|
2015-01-09 11:36:03 +00:00
|
|
|
fn shr(self, rhs: usize) -> BigInt {
|
2014-12-16 14:38:35 +00:00
|
|
|
BigInt::from_biguint(self.sign, &self.data >> rhs)
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Zero for BigInt {
|
|
|
|
#[inline]
|
|
|
|
fn zero() -> BigInt {
|
2014-09-21 00:58:59 +00:00
|
|
|
BigInt::from_biguint(NoSign, Zero::zero())
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
2014-09-21 00:58:59 +00:00
|
|
|
fn is_zero(&self) -> bool { self.sign == NoSign }
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl One for BigInt {
|
|
|
|
#[inline]
|
|
|
|
fn one() -> BigInt {
|
|
|
|
BigInt::from_biguint(Plus, One::one())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Signed for BigInt {
|
|
|
|
#[inline]
|
|
|
|
fn abs(&self) -> BigInt {
|
|
|
|
match self.sign {
|
2014-09-21 00:58:59 +00:00
|
|
|
Plus | NoSign => self.clone(),
|
2014-09-16 17:35:35 +00:00
|
|
|
Minus => BigInt::from_biguint(Plus, self.data.clone())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn abs_sub(&self, other: &BigInt) -> BigInt {
|
2014-12-16 14:38:35 +00:00
|
|
|
if *self <= *other { Zero::zero() } else { self - other }
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn signum(&self) -> BigInt {
|
|
|
|
match self.sign {
|
|
|
|
Plus => BigInt::from_biguint(Plus, One::one()),
|
|
|
|
Minus => BigInt::from_biguint(Minus, One::one()),
|
2014-09-21 00:58:59 +00:00
|
|
|
NoSign => Zero::zero(),
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn is_positive(&self) -> bool { self.sign == Plus }
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn is_negative(&self) -> bool { self.sign == Minus }
|
|
|
|
}
|
|
|
|
|
2015-11-16 19:04:41 +00:00
|
|
|
// We want to forward to BigUint::add, but it's not clear how that will go until
|
|
|
|
// we compare both sign and magnitude. So we duplicate this body for every
|
|
|
|
// val/ref combination, deferring that decision to BigUint's own forwarding.
|
|
|
|
macro_rules! bigint_add {
|
|
|
|
($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => {
|
|
|
|
match ($a.sign, $b.sign) {
|
|
|
|
(_, NoSign) => $a_owned,
|
|
|
|
(NoSign, _) => $b_owned,
|
|
|
|
// same sign => keep the sign with the sum of magnitudes
|
|
|
|
(Plus, Plus) | (Minus, Minus) =>
|
|
|
|
BigInt::from_biguint($a.sign, $a_data + $b_data),
|
|
|
|
// opposite signs => keep the sign of the larger with the difference of magnitudes
|
|
|
|
(Plus, Minus) | (Minus, Plus) =>
|
|
|
|
match $a.data.cmp(&$b.data) {
|
|
|
|
Less => BigInt::from_biguint($b.sign, $b_data - $a_data),
|
|
|
|
Greater => BigInt::from_biguint($a.sign, $a_data - $b_data),
|
|
|
|
Equal => Zero::zero(),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
2014-12-16 14:38:35 +00:00
|
|
|
|
2015-01-04 16:49:46 +00:00
|
|
|
impl<'a, 'b> Add<&'b BigInt> for &'a BigInt {
|
|
|
|
type Output = BigInt;
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[inline]
|
2014-12-16 14:38:35 +00:00
|
|
|
fn add(self, other: &BigInt) -> BigInt {
|
2015-11-16 19:04:41 +00:00
|
|
|
bigint_add!(self, self.clone(), &self.data, other, other.clone(), &other.data)
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-16 19:04:41 +00:00
|
|
|
impl<'a> Add<BigInt> for &'a BigInt {
|
|
|
|
type Output = BigInt;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn add(self, other: BigInt) -> BigInt {
|
|
|
|
bigint_add!(self, self.clone(), &self.data, other, other, other.data)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> Add<&'a BigInt> for BigInt {
|
|
|
|
type Output = BigInt;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn add(self, other: &BigInt) -> BigInt {
|
|
|
|
bigint_add!(self, self, self.data, other, other.clone(), &other.data)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Add<BigInt> for BigInt {
|
|
|
|
type Output = BigInt;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn add(self, other: BigInt) -> BigInt {
|
|
|
|
bigint_add!(self, self, self.data, other, other, other.data)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// We want to forward to BigUint::sub, but it's not clear how that will go until
|
|
|
|
// we compare both sign and magnitude. So we duplicate this body for every
|
|
|
|
// val/ref combination, deferring that decision to BigUint's own forwarding.
|
|
|
|
macro_rules! bigint_sub {
|
|
|
|
($a:expr, $a_owned:expr, $a_data:expr, $b:expr, $b_owned:expr, $b_data:expr) => {
|
|
|
|
match ($a.sign, $b.sign) {
|
|
|
|
(_, NoSign) => $a_owned,
|
|
|
|
(NoSign, _) => -$b_owned,
|
|
|
|
// opposite signs => keep the sign of the left with the sum of magnitudes
|
|
|
|
(Plus, Minus) | (Minus, Plus) =>
|
|
|
|
BigInt::from_biguint($a.sign, $a_data + $b_data),
|
|
|
|
// same sign => keep or toggle the sign of the left with the difference of magnitudes
|
|
|
|
(Plus, Plus) | (Minus, Minus) =>
|
|
|
|
match $a.data.cmp(&$b.data) {
|
|
|
|
Less => BigInt::from_biguint(-$a.sign, $b_data - $a_data),
|
|
|
|
Greater => BigInt::from_biguint($a.sign, $a_data - $b_data),
|
|
|
|
Equal => Zero::zero(),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
2014-12-16 14:38:35 +00:00
|
|
|
|
2015-01-04 16:49:46 +00:00
|
|
|
impl<'a, 'b> Sub<&'b BigInt> for &'a BigInt {
|
|
|
|
type Output = BigInt;
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[inline]
|
2014-12-16 14:38:35 +00:00
|
|
|
fn sub(self, other: &BigInt) -> BigInt {
|
2015-11-16 19:04:41 +00:00
|
|
|
bigint_sub!(self, self.clone(), &self.data, other, other.clone(), &other.data)
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-16 19:04:41 +00:00
|
|
|
impl<'a> Sub<BigInt> for &'a BigInt {
|
|
|
|
type Output = BigInt;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn sub(self, other: BigInt) -> BigInt {
|
|
|
|
bigint_sub!(self, self.clone(), &self.data, other, other, other.data)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> Sub<&'a BigInt> for BigInt {
|
|
|
|
type Output = BigInt;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn sub(self, other: &BigInt) -> BigInt {
|
|
|
|
bigint_sub!(self, self, self.data, other, other.clone(), &other.data)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Sub<BigInt> for BigInt {
|
|
|
|
type Output = BigInt;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn sub(self, other: BigInt) -> BigInt {
|
|
|
|
bigint_sub!(self, self, self.data, other, other, other.data)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// We want to forward to BigUint::mul, and defer the val/ref decision to
|
|
|
|
// BigUint, so we duplicate this body for every val/ref combination.
|
|
|
|
macro_rules! bigint_mul {
|
|
|
|
($a:expr, $a_data:expr, $b:expr, $b_data:expr) => {
|
|
|
|
BigInt::from_biguint($a.sign * $b.sign, $a_data * $b_data)
|
|
|
|
};
|
|
|
|
}
|
2014-12-16 14:38:35 +00:00
|
|
|
|
2015-01-04 16:49:46 +00:00
|
|
|
impl<'a, 'b> Mul<&'b BigInt> for &'a BigInt {
|
|
|
|
type Output = BigInt;
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[inline]
|
2014-12-16 14:38:35 +00:00
|
|
|
fn mul(self, other: &BigInt) -> BigInt {
|
2015-11-16 19:04:41 +00:00
|
|
|
bigint_mul!(self, &self.data, other, &other.data)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> Mul<BigInt> for &'a BigInt {
|
|
|
|
type Output = BigInt;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn mul(self, other: BigInt) -> BigInt {
|
|
|
|
bigint_mul!(self, &self.data, other, other.data)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> Mul<&'a BigInt> for BigInt {
|
|
|
|
type Output = BigInt;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn mul(self, other: &BigInt) -> BigInt {
|
|
|
|
bigint_mul!(self, self.data, other, &other.data)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Mul<BigInt> for BigInt {
|
|
|
|
type Output = BigInt;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn mul(self, other: BigInt) -> BigInt {
|
|
|
|
bigint_mul!(self, self.data, other, other.data)
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-16 19:04:41 +00:00
|
|
|
forward_all_binop_to_ref_ref!(impl Div for BigInt, div);
|
2014-12-16 14:38:35 +00:00
|
|
|
|
2015-01-04 16:49:46 +00:00
|
|
|
impl<'a, 'b> Div<&'b BigInt> for &'a BigInt {
|
|
|
|
type Output = BigInt;
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[inline]
|
2014-12-16 14:38:35 +00:00
|
|
|
fn div(self, other: &BigInt) -> BigInt {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (q, _) = self.div_rem(other);
|
|
|
|
q
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-16 19:04:41 +00:00
|
|
|
forward_all_binop_to_ref_ref!(impl Rem for BigInt, rem);
|
2014-12-16 14:38:35 +00:00
|
|
|
|
2015-01-04 16:49:46 +00:00
|
|
|
impl<'a, 'b> Rem<&'b BigInt> for &'a BigInt {
|
|
|
|
type Output = BigInt;
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[inline]
|
2014-12-16 14:38:35 +00:00
|
|
|
fn rem(self, other: &BigInt) -> BigInt {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (_, r) = self.div_rem(other);
|
|
|
|
r
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-04 16:49:46 +00:00
|
|
|
impl Neg for BigInt {
|
|
|
|
type Output = BigInt;
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[inline]
|
2015-11-16 19:04:41 +00:00
|
|
|
fn neg(mut self) -> BigInt {
|
|
|
|
self.sign = -self.sign;
|
|
|
|
self
|
|
|
|
}
|
2014-12-21 10:41:03 +00:00
|
|
|
}
|
|
|
|
|
2015-01-04 16:49:46 +00:00
|
|
|
impl<'a> Neg for &'a BigInt {
|
|
|
|
type Output = BigInt;
|
|
|
|
|
2014-12-21 10:41:03 +00:00
|
|
|
#[inline]
|
|
|
|
fn neg(self) -> BigInt {
|
2015-11-16 19:04:41 +00:00
|
|
|
-self.clone()
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl CheckedAdd for BigInt {
|
|
|
|
#[inline]
|
|
|
|
fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
|
|
|
|
return Some(self.add(v));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl CheckedSub for BigInt {
|
|
|
|
#[inline]
|
|
|
|
fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
|
|
|
|
return Some(self.sub(v));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl CheckedMul for BigInt {
|
|
|
|
#[inline]
|
|
|
|
fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
|
|
|
|
return Some(self.mul(v));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl CheckedDiv for BigInt {
|
|
|
|
#[inline]
|
|
|
|
fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
|
|
|
|
if v.is_zero() {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
return Some(self.div(v));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Integer for BigInt {
|
|
|
|
#[inline]
|
|
|
|
fn div_rem(&self, other: &BigInt) -> (BigInt, BigInt) {
|
|
|
|
// r.sign == self.sign
|
|
|
|
let (d_ui, r_ui) = self.data.div_mod_floor(&other.data);
|
2015-11-16 19:04:41 +00:00
|
|
|
let d = BigInt::from_biguint(self.sign, d_ui);
|
|
|
|
let r = BigInt::from_biguint(self.sign, r_ui);
|
|
|
|
if other.is_negative() { (-d, r) } else { (d, r) }
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn div_floor(&self, other: &BigInt) -> BigInt {
|
|
|
|
let (d, _) = self.div_mod_floor(other);
|
|
|
|
d
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn mod_floor(&self, other: &BigInt) -> BigInt {
|
|
|
|
let (_, m) = self.div_mod_floor(other);
|
|
|
|
m
|
|
|
|
}
|
|
|
|
|
|
|
|
fn div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt) {
|
|
|
|
// m.sign == other.sign
|
|
|
|
let (d_ui, m_ui) = self.data.div_rem(&other.data);
|
|
|
|
let d = BigInt::from_biguint(Plus, d_ui);
|
|
|
|
let m = BigInt::from_biguint(Plus, m_ui);
|
2014-12-16 14:38:35 +00:00
|
|
|
let one: BigInt = One::one();
|
2014-09-16 17:35:35 +00:00
|
|
|
match (self.sign, other.sign) {
|
2014-10-30 13:20:15 +00:00
|
|
|
(_, NoSign) => panic!(),
|
2014-09-21 00:58:59 +00:00
|
|
|
(Plus, Plus) | (NoSign, Plus) => (d, m),
|
2014-12-16 14:38:35 +00:00
|
|
|
(Plus, Minus) | (NoSign, Minus) => {
|
|
|
|
if m.is_zero() {
|
|
|
|
(-d, Zero::zero())
|
|
|
|
} else {
|
|
|
|
(-d - one, m + other)
|
|
|
|
}
|
2014-09-16 17:35:35 +00:00
|
|
|
},
|
2014-12-16 14:38:35 +00:00
|
|
|
(Minus, Plus) => {
|
|
|
|
if m.is_zero() {
|
|
|
|
(-d, Zero::zero())
|
|
|
|
} else {
|
|
|
|
(-d - one, other - m)
|
|
|
|
}
|
|
|
|
}
|
2014-09-16 17:35:35 +00:00
|
|
|
(Minus, Minus) => (d, -m)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
|
|
|
|
///
|
|
|
|
/// The result is always positive.
|
|
|
|
#[inline]
|
|
|
|
fn gcd(&self, other: &BigInt) -> BigInt {
|
|
|
|
BigInt::from_biguint(Plus, self.data.gcd(&other.data))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
|
|
|
|
#[inline]
|
|
|
|
fn lcm(&self, other: &BigInt) -> BigInt {
|
|
|
|
BigInt::from_biguint(Plus, self.data.lcm(&other.data))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Deprecated, use `is_multiple_of` instead.
|
|
|
|
#[inline]
|
|
|
|
fn divides(&self, other: &BigInt) -> bool { return self.is_multiple_of(other); }
|
|
|
|
|
|
|
|
/// Returns `true` if the number is a multiple of `other`.
|
|
|
|
#[inline]
|
|
|
|
fn is_multiple_of(&self, other: &BigInt) -> bool { self.data.is_multiple_of(&other.data) }
|
|
|
|
|
|
|
|
/// Returns `true` if the number is divisible by `2`.
|
|
|
|
#[inline]
|
|
|
|
fn is_even(&self) -> bool { self.data.is_even() }
|
|
|
|
|
|
|
|
/// Returns `true` if the number is not divisible by `2`.
|
|
|
|
#[inline]
|
|
|
|
fn is_odd(&self) -> bool { self.data.is_odd() }
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ToPrimitive for BigInt {
|
|
|
|
#[inline]
|
|
|
|
fn to_i64(&self) -> Option<i64> {
|
|
|
|
match self.sign {
|
|
|
|
Plus => self.data.to_i64(),
|
2014-09-21 00:58:59 +00:00
|
|
|
NoSign => Some(0),
|
2014-09-16 17:35:35 +00:00
|
|
|
Minus => {
|
|
|
|
self.data.to_u64().and_then(|n| {
|
|
|
|
let m: u64 = 1 << 63;
|
|
|
|
if n < m {
|
|
|
|
Some(-(n as i64))
|
|
|
|
} else if n == m {
|
|
|
|
Some(i64::MIN)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn to_u64(&self) -> Option<u64> {
|
|
|
|
match self.sign {
|
|
|
|
Plus => self.data.to_u64(),
|
2014-09-21 00:58:59 +00:00
|
|
|
NoSign => Some(0),
|
2014-09-16 17:35:35 +00:00
|
|
|
Minus => None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl FromPrimitive for BigInt {
|
|
|
|
#[inline]
|
|
|
|
fn from_i64(n: i64) -> Option<BigInt> {
|
2015-11-16 19:04:41 +00:00
|
|
|
if n >= 0 {
|
|
|
|
FromPrimitive::from_u64(n as u64)
|
2014-09-16 17:35:35 +00:00
|
|
|
} else {
|
2015-11-16 19:04:41 +00:00
|
|
|
let u = u64::MAX - (n as u64) + 1;
|
|
|
|
FromPrimitive::from_u64(u).map(|n| {
|
|
|
|
BigInt::from_biguint(Minus, n)
|
|
|
|
})
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn from_u64(n: u64) -> Option<BigInt> {
|
|
|
|
if n == 0 {
|
|
|
|
Some(Zero::zero())
|
|
|
|
} else {
|
2015-11-16 19:04:41 +00:00
|
|
|
FromPrimitive::from_u64(n).map(|n| {
|
|
|
|
BigInt::from_biguint(Plus, n)
|
2014-09-16 17:35:35 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A generic trait for converting a value to a `BigInt`.
|
|
|
|
pub trait ToBigInt {
|
|
|
|
/// Converts the value of `self` to a `BigInt`.
|
|
|
|
fn to_bigint(&self) -> Option<BigInt>;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ToBigInt for BigInt {
|
|
|
|
#[inline]
|
|
|
|
fn to_bigint(&self) -> Option<BigInt> {
|
|
|
|
Some(self.clone())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ToBigInt for BigUint {
|
|
|
|
#[inline]
|
|
|
|
fn to_bigint(&self) -> Option<BigInt> {
|
|
|
|
if self.is_zero() {
|
|
|
|
Some(Zero::zero())
|
|
|
|
} else {
|
|
|
|
Some(BigInt { sign: Plus, data: self.clone() })
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-12-19 02:01:24 +00:00
|
|
|
macro_rules! impl_to_bigint {
|
2014-09-16 17:35:35 +00:00
|
|
|
($T:ty, $from_ty:path) => {
|
|
|
|
impl ToBigInt for $T {
|
|
|
|
#[inline]
|
|
|
|
fn to_bigint(&self) -> Option<BigInt> {
|
|
|
|
$from_ty(*self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2014-12-19 02:01:24 +00:00
|
|
|
}
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2015-03-04 17:45:19 +00:00
|
|
|
impl_to_bigint!(isize, FromPrimitive::from_isize);
|
2014-12-19 02:01:24 +00:00
|
|
|
impl_to_bigint!(i8, FromPrimitive::from_i8);
|
|
|
|
impl_to_bigint!(i16, FromPrimitive::from_i16);
|
|
|
|
impl_to_bigint!(i32, FromPrimitive::from_i32);
|
|
|
|
impl_to_bigint!(i64, FromPrimitive::from_i64);
|
2015-03-04 17:45:19 +00:00
|
|
|
impl_to_bigint!(usize, FromPrimitive::from_usize);
|
2014-12-19 02:01:24 +00:00
|
|
|
impl_to_bigint!(u8, FromPrimitive::from_u8);
|
|
|
|
impl_to_bigint!(u16, FromPrimitive::from_u16);
|
|
|
|
impl_to_bigint!(u32, FromPrimitive::from_u32);
|
|
|
|
impl_to_bigint!(u64, FromPrimitive::from_u64);
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
pub trait RandBigInt {
|
|
|
|
/// Generate a random `BigUint` of the given bit size.
|
2015-01-09 21:54:32 +00:00
|
|
|
fn gen_biguint(&mut self, bit_size: usize) -> BigUint;
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
/// Generate a random BigInt of the given bit size.
|
2015-01-09 11:36:03 +00:00
|
|
|
fn gen_bigint(&mut self, bit_size: usize) -> BigInt;
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
/// Generate a random `BigUint` less than the given bound. Fails
|
|
|
|
/// when the bound is zero.
|
2015-01-09 21:54:32 +00:00
|
|
|
fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint;
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
/// Generate a random `BigUint` within the given range. The lower
|
|
|
|
/// bound is inclusive; the upper bound is exclusive. Fails when
|
|
|
|
/// the upper bound is not greater than the lower bound.
|
2015-01-09 21:54:32 +00:00
|
|
|
fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint;
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
/// Generate a random `BigInt` within the given range. The lower
|
|
|
|
/// bound is inclusive; the upper bound is exclusive. Fails when
|
|
|
|
/// the upper bound is not greater than the lower bound.
|
|
|
|
fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<R: Rng> RandBigInt for R {
|
2015-01-09 21:54:32 +00:00
|
|
|
fn gen_biguint(&mut self, bit_size: usize) -> BigUint {
|
2015-01-20 19:17:41 +00:00
|
|
|
let (digits, rem) = bit_size.div_rem(&big_digit::BITS);
|
2014-09-16 17:35:35 +00:00
|
|
|
let mut data = Vec::with_capacity(digits+1);
|
2015-10-19 13:43:47 +00:00
|
|
|
for _ in 0 .. digits {
|
2014-09-16 17:35:35 +00:00
|
|
|
data.push(self.gen());
|
|
|
|
}
|
|
|
|
if rem > 0 {
|
|
|
|
let final_digit: BigDigit = self.gen();
|
2015-01-20 19:17:41 +00:00
|
|
|
data.push(final_digit >> (big_digit::BITS - rem));
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
BigUint::new(data)
|
|
|
|
}
|
|
|
|
|
2015-01-09 11:36:03 +00:00
|
|
|
fn gen_bigint(&mut self, bit_size: usize) -> BigInt {
|
2014-09-16 17:35:35 +00:00
|
|
|
// Generate a random BigUint...
|
2015-01-09 21:54:32 +00:00
|
|
|
let biguint = self.gen_biguint(bit_size);
|
2014-09-16 17:35:35 +00:00
|
|
|
// ...and then randomly assign it a Sign...
|
2015-01-09 21:54:32 +00:00
|
|
|
let sign = if biguint.is_zero() {
|
2014-09-16 17:35:35 +00:00
|
|
|
// ...except that if the BigUint is zero, we need to try
|
|
|
|
// again with probability 0.5. This is because otherwise,
|
|
|
|
// the probability of generating a zero BigInt would be
|
|
|
|
// double that of any other number.
|
|
|
|
if self.gen() {
|
|
|
|
return self.gen_bigint(bit_size);
|
|
|
|
} else {
|
2014-09-21 00:58:59 +00:00
|
|
|
NoSign
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
} else if self.gen() {
|
|
|
|
Plus
|
|
|
|
} else {
|
|
|
|
Minus
|
|
|
|
};
|
2015-01-09 21:54:32 +00:00
|
|
|
BigInt::from_biguint(sign, biguint)
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
2015-01-09 21:54:32 +00:00
|
|
|
fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint {
|
2014-09-16 17:35:35 +00:00
|
|
|
assert!(!bound.is_zero());
|
|
|
|
let bits = bound.bits();
|
|
|
|
loop {
|
2015-01-09 21:54:32 +00:00
|
|
|
let n = self.gen_biguint(bits);
|
2014-09-16 17:35:35 +00:00
|
|
|
if n < *bound { return n; }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-09 21:54:32 +00:00
|
|
|
fn gen_biguint_range(&mut self,
|
2014-09-16 17:35:35 +00:00
|
|
|
lbound: &BigUint,
|
|
|
|
ubound: &BigUint)
|
|
|
|
-> BigUint {
|
|
|
|
assert!(*lbound < *ubound);
|
2015-01-09 21:54:32 +00:00
|
|
|
return lbound + self.gen_biguint_below(&(ubound - lbound));
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn gen_bigint_range(&mut self,
|
|
|
|
lbound: &BigInt,
|
|
|
|
ubound: &BigInt)
|
|
|
|
-> BigInt {
|
|
|
|
assert!(*lbound < *ubound);
|
2015-01-09 21:54:32 +00:00
|
|
|
let delta = (ubound - lbound).to_biguint().unwrap();
|
|
|
|
return lbound + self.gen_biguint_below(&delta).to_bigint().unwrap();
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl BigInt {
|
|
|
|
/// Creates and initializes a BigInt.
|
|
|
|
///
|
2015-01-20 23:52:18 +00:00
|
|
|
/// The digits are in little-endian base 2^32.
|
2014-09-16 17:35:35 +00:00
|
|
|
#[inline]
|
|
|
|
pub fn new(sign: Sign, digits: Vec<BigDigit>) -> BigInt {
|
|
|
|
BigInt::from_biguint(sign, BigUint::new(digits))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Creates and initializes a `BigInt`.
|
|
|
|
///
|
2015-01-20 23:52:18 +00:00
|
|
|
/// The digits are in little-endian base 2^32.
|
2014-09-16 17:35:35 +00:00
|
|
|
#[inline]
|
|
|
|
pub fn from_biguint(sign: Sign, data: BigUint) -> BigInt {
|
2014-09-21 00:58:59 +00:00
|
|
|
if sign == NoSign || data.is_zero() {
|
|
|
|
return BigInt { sign: NoSign, data: Zero::zero() };
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
BigInt { sign: sign, data: data }
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Creates and initializes a `BigInt`.
|
|
|
|
#[inline]
|
|
|
|
pub fn from_slice(sign: Sign, slice: &[BigDigit]) -> BigInt {
|
|
|
|
BigInt::from_biguint(sign, BigUint::from_slice(slice))
|
|
|
|
}
|
|
|
|
|
2015-01-21 01:38:51 +00:00
|
|
|
/// Creates and initializes a `BigInt`.
|
|
|
|
///
|
|
|
|
/// The bytes are in big-endian byte order.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use num::bigint::{BigInt, Sign};
|
|
|
|
///
|
2015-04-15 19:43:37 +00:00
|
|
|
/// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"A"),
|
|
|
|
/// BigInt::parse_bytes(b"65", 10).unwrap());
|
|
|
|
/// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AA"),
|
|
|
|
/// BigInt::parse_bytes(b"16705", 10).unwrap());
|
|
|
|
/// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"AB"),
|
|
|
|
/// BigInt::parse_bytes(b"16706", 10).unwrap());
|
|
|
|
/// assert_eq!(BigInt::from_bytes_be(Sign::Plus, b"Hello world!"),
|
|
|
|
/// BigInt::parse_bytes(b"22405534230753963835153736737", 10).unwrap());
|
2015-01-21 01:38:51 +00:00
|
|
|
/// ```
|
|
|
|
#[inline]
|
|
|
|
pub fn from_bytes_be(sign: Sign, bytes: &[u8]) -> BigInt {
|
|
|
|
BigInt::from_biguint(sign, BigUint::from_bytes_be(bytes))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Creates and initializes a `BigInt`.
|
|
|
|
///
|
|
|
|
/// The bytes are in little-endian byte order.
|
|
|
|
#[inline]
|
|
|
|
pub fn from_bytes_le(sign: Sign, bytes: &[u8]) -> BigInt {
|
|
|
|
BigInt::from_biguint(sign, BigUint::from_bytes_le(bytes))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the sign and the byte representation of the `BigInt` in little-endian byte order.
|
2015-04-15 19:43:37 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use num::bigint::{ToBigInt, Sign};
|
|
|
|
///
|
|
|
|
/// let i = -1125.to_bigint().unwrap();
|
|
|
|
/// assert_eq!(i.to_bytes_le(), (Sign::Minus, vec![101, 4]));
|
|
|
|
/// ```
|
2015-01-21 01:38:51 +00:00
|
|
|
#[inline]
|
|
|
|
pub fn to_bytes_le(&self) -> (Sign, Vec<u8>) {
|
|
|
|
(self.sign, self.data.to_bytes_le())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the sign and the byte representation of the `BigInt` in big-endian byte order.
|
2015-04-15 19:43:37 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use num::bigint::{ToBigInt, Sign};
|
|
|
|
///
|
|
|
|
/// let i = -1125.to_bigint().unwrap();
|
|
|
|
/// assert_eq!(i.to_bytes_be(), (Sign::Minus, vec![4, 101]));
|
|
|
|
/// ```
|
2015-01-21 01:38:51 +00:00
|
|
|
#[inline]
|
|
|
|
pub fn to_bytes_be(&self) -> (Sign, Vec<u8>) {
|
|
|
|
(self.sign, self.data.to_bytes_be())
|
|
|
|
}
|
|
|
|
|
2015-11-09 20:50:25 +00:00
|
|
|
/// Returns the integer formatted as a string in the given radix.
|
|
|
|
/// `radix` must be in the range `[2, 36]`.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use num::bigint::BigInt;
|
|
|
|
///
|
|
|
|
/// let i = BigInt::parse_bytes(b"ff", 16).unwrap();
|
|
|
|
/// assert_eq!(i.to_str_radix(16), "ff");
|
|
|
|
/// ```
|
|
|
|
#[inline]
|
|
|
|
pub fn to_str_radix(&self, radix: u32) -> String {
|
|
|
|
let mut v = to_str_radix_reversed(&self.data, radix);
|
|
|
|
|
|
|
|
if self.is_negative() {
|
|
|
|
v.push(b'-');
|
|
|
|
}
|
|
|
|
|
|
|
|
v.reverse();
|
|
|
|
unsafe { String::from_utf8_unchecked(v) }
|
|
|
|
}
|
|
|
|
|
2015-10-06 07:32:32 +00:00
|
|
|
/// Returns the sign of the `BigInt` as a `Sign`.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use num::bigint::{ToBigInt, Sign};
|
|
|
|
///
|
|
|
|
/// assert_eq!(ToBigInt::to_bigint(&1234).unwrap().sign(), Sign::Plus);
|
|
|
|
/// assert_eq!(ToBigInt::to_bigint(&-4321).unwrap().sign(), Sign::Minus);
|
|
|
|
/// assert_eq!(ToBigInt::to_bigint(&0).unwrap().sign(), Sign::NoSign);
|
|
|
|
/// ```
|
|
|
|
#[inline]
|
|
|
|
pub fn sign(&self) -> Sign {
|
|
|
|
self.sign
|
|
|
|
}
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
/// Creates and initializes a `BigInt`.
|
2015-01-20 23:52:18 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use num::bigint::{BigInt, ToBigInt};
|
|
|
|
///
|
2015-04-15 19:43:37 +00:00
|
|
|
/// assert_eq!(BigInt::parse_bytes(b"1234", 10), ToBigInt::to_bigint(&1234));
|
|
|
|
/// assert_eq!(BigInt::parse_bytes(b"ABCD", 16), ToBigInt::to_bigint(&0xABCD));
|
|
|
|
/// assert_eq!(BigInt::parse_bytes(b"G", 16), None);
|
2015-01-20 23:52:18 +00:00
|
|
|
/// ```
|
2014-11-04 14:20:37 +00:00
|
|
|
#[inline]
|
2015-02-19 00:29:46 +00:00
|
|
|
pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigInt> {
|
2015-04-03 06:29:17 +00:00
|
|
|
str::from_utf8(buf).ok().and_then(|s| BigInt::from_str_radix(s, radix).ok())
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
2014-11-04 14:20:37 +00:00
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
/// Converts this `BigInt` into a `BigUint`, if it's not negative.
|
|
|
|
#[inline]
|
2015-01-09 21:54:32 +00:00
|
|
|
pub fn to_biguint(&self) -> Option<BigUint> {
|
2014-09-16 17:35:35 +00:00
|
|
|
match self.sign {
|
|
|
|
Plus => Some(self.data.clone()),
|
2014-09-21 00:58:59 +00:00
|
|
|
NoSign => Some(Zero::zero()),
|
2014-09-16 17:35:35 +00:00
|
|
|
Minus => None
|
|
|
|
}
|
|
|
|
}
|
2014-11-15 03:30:48 +00:00
|
|
|
|
|
|
|
#[inline]
|
|
|
|
pub fn checked_add(&self, v: &BigInt) -> Option<BigInt> {
|
|
|
|
return Some(self.add(v));
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
pub fn checked_sub(&self, v: &BigInt) -> Option<BigInt> {
|
|
|
|
return Some(self.sub(v));
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
pub fn checked_mul(&self, v: &BigInt) -> Option<BigInt> {
|
|
|
|
return Some(self.mul(v));
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
pub fn checked_div(&self, v: &BigInt) -> Option<BigInt> {
|
|
|
|
if v.is_zero() {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
return Some(self.div(v));
|
|
|
|
}
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
2015-02-03 19:42:46 +00:00
|
|
|
#[derive(Debug, PartialEq)]
|
|
|
|
pub enum ParseBigIntError {
|
|
|
|
ParseInt(ParseIntError),
|
|
|
|
Other,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Display for ParseBigIntError {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
match self {
|
|
|
|
&ParseBigIntError::ParseInt(ref e) => e.fmt(f),
|
|
|
|
&ParseBigIntError::Other => "failed to parse provided string".fmt(f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Error for ParseBigIntError {
|
|
|
|
fn description(&self) -> &str { "failed to parse bigint/biguint" }
|
|
|
|
}
|
|
|
|
|
2015-04-02 10:37:57 +00:00
|
|
|
impl From<ParseIntError> for ParseBigIntError {
|
|
|
|
fn from(err: ParseIntError) -> ParseBigIntError {
|
2015-02-03 19:42:46 +00:00
|
|
|
ParseBigIntError::ParseInt(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[cfg(test)]
|
2015-01-09 21:54:32 +00:00
|
|
|
mod biguint_tests {
|
2014-09-16 17:35:35 +00:00
|
|
|
use Integer;
|
2015-11-09 20:50:25 +00:00
|
|
|
use super::{BigDigit, BigUint, ToBigUint, big_digit};
|
2014-11-18 12:09:53 +00:00
|
|
|
use super::{BigInt, RandBigInt, ToBigInt};
|
|
|
|
use super::Sign::Plus;
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2014-12-23 16:12:57 +00:00
|
|
|
use std::cmp::Ordering::{Less, Equal, Greater};
|
2014-09-16 17:35:35 +00:00
|
|
|
use std::i64;
|
2014-12-23 17:50:53 +00:00
|
|
|
use std::iter::repeat;
|
|
|
|
use std::str::FromStr;
|
2014-09-16 17:35:35 +00:00
|
|
|
use std::u64;
|
|
|
|
|
2015-02-05 16:20:16 +00:00
|
|
|
use rand::thread_rng;
|
2015-04-03 06:29:17 +00:00
|
|
|
use {Num, Zero, One, CheckedAdd, CheckedSub, CheckedMul, CheckedDiv};
|
|
|
|
use {ToPrimitive, FromPrimitive};
|
2014-11-15 03:30:48 +00:00
|
|
|
|
2015-11-16 19:06:39 +00:00
|
|
|
/// Assert that an op works for all val/ref combinations
|
|
|
|
macro_rules! assert_op {
|
|
|
|
($left:ident $op:tt $right:ident == $expected:expr) => {
|
|
|
|
assert_eq!((&$left) $op (&$right), $expected);
|
|
|
|
assert_eq!((&$left) $op $right.clone(), $expected);
|
|
|
|
assert_eq!($left.clone() $op (&$right), $expected);
|
|
|
|
assert_eq!($left.clone() $op $right.clone(), $expected);
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[test]
|
|
|
|
fn test_from_slice() {
|
|
|
|
fn check(slice: &[BigDigit], data: &[BigDigit]) {
|
2015-04-02 16:37:32 +00:00
|
|
|
assert!(BigUint::from_slice(slice).data == data);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
2014-11-20 20:21:06 +00:00
|
|
|
check(&[1], &[1]);
|
|
|
|
check(&[0, 0, 0], &[]);
|
|
|
|
check(&[1, 2, 0, 0], &[1, 2]);
|
|
|
|
check(&[0, 0, 1, 2], &[0, 0, 1, 2]);
|
|
|
|
check(&[0, 0, 1, 2, 0, 0], &[0, 0, 1, 2]);
|
2015-04-03 06:29:17 +00:00
|
|
|
check(&[-1i32 as BigDigit], &[-1i32 as BigDigit]);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
2015-01-21 01:38:51 +00:00
|
|
|
#[test]
|
|
|
|
fn test_from_bytes_be() {
|
|
|
|
fn check(s: &str, result: &str) {
|
|
|
|
assert_eq!(BigUint::from_bytes_be(s.as_bytes()),
|
|
|
|
BigUint::parse_bytes(result.as_bytes(), 10).unwrap());
|
|
|
|
}
|
|
|
|
check("A", "65");
|
|
|
|
check("AA", "16705");
|
|
|
|
check("AB", "16706");
|
|
|
|
check("Hello world!", "22405534230753963835153736737");
|
|
|
|
assert_eq!(BigUint::from_bytes_be(&[]), Zero::zero());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_to_bytes_be() {
|
|
|
|
fn check(s: &str, result: &str) {
|
|
|
|
let b = BigUint::parse_bytes(result.as_bytes(), 10).unwrap();
|
2015-04-02 16:37:32 +00:00
|
|
|
assert_eq!(b.to_bytes_be(), s.as_bytes());
|
2015-01-21 01:38:51 +00:00
|
|
|
}
|
|
|
|
check("A", "65");
|
|
|
|
check("AA", "16705");
|
|
|
|
check("AB", "16706");
|
|
|
|
check("Hello world!", "22405534230753963835153736737");
|
|
|
|
let b: BigUint = Zero::zero();
|
|
|
|
assert_eq!(b.to_bytes_be(), [0]);
|
|
|
|
|
|
|
|
// Test with leading/trailing zero bytes and a full BigDigit of value 0
|
2015-04-03 06:29:17 +00:00
|
|
|
let b = BigUint::from_str_radix("00010000000000000200", 16).unwrap();
|
2015-01-21 01:38:51 +00:00
|
|
|
assert_eq!(b.to_bytes_be(), [1, 0, 0, 0, 0, 0, 0, 2, 0]);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_from_bytes_le() {
|
|
|
|
fn check(s: &str, result: &str) {
|
|
|
|
assert_eq!(BigUint::from_bytes_le(s.as_bytes()),
|
|
|
|
BigUint::parse_bytes(result.as_bytes(), 10).unwrap());
|
|
|
|
}
|
|
|
|
check("A", "65");
|
|
|
|
check("AA", "16705");
|
|
|
|
check("BA", "16706");
|
|
|
|
check("!dlrow olleH", "22405534230753963835153736737");
|
|
|
|
assert_eq!(BigUint::from_bytes_le(&[]), Zero::zero());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_to_bytes_le() {
|
|
|
|
fn check(s: &str, result: &str) {
|
|
|
|
let b = BigUint::parse_bytes(result.as_bytes(), 10).unwrap();
|
2015-04-02 16:37:32 +00:00
|
|
|
assert_eq!(b.to_bytes_le(), s.as_bytes());
|
2015-01-21 01:38:51 +00:00
|
|
|
}
|
|
|
|
check("A", "65");
|
|
|
|
check("AA", "16705");
|
|
|
|
check("BA", "16706");
|
|
|
|
check("!dlrow olleH", "22405534230753963835153736737");
|
|
|
|
let b: BigUint = Zero::zero();
|
|
|
|
assert_eq!(b.to_bytes_le(), [0]);
|
|
|
|
|
|
|
|
// Test with leading/trailing zero bytes and a full BigDigit of value 0
|
2015-04-03 06:29:17 +00:00
|
|
|
let b = BigUint::from_str_radix("00010000000000000200", 16).unwrap();
|
2015-01-21 01:38:51 +00:00
|
|
|
assert_eq!(b.to_bytes_le(), [0, 2, 0, 0, 0, 0, 0, 0, 1]);
|
|
|
|
}
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[test]
|
|
|
|
fn test_cmp() {
|
2015-08-10 19:11:56 +00:00
|
|
|
let data: [&[_]; 7] = [ &[], &[1], &[2], &[!0], &[0, 1], &[2, 1], &[1, 1, 1] ];
|
2014-09-16 17:35:35 +00:00
|
|
|
let data: Vec<BigUint> = data.iter().map(|v| BigUint::from_slice(*v)).collect();
|
|
|
|
for (i, ni) in data.iter().enumerate() {
|
2015-01-23 16:54:55 +00:00
|
|
|
for (j0, nj) in data[i..].iter().enumerate() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let j = j0 + i;
|
|
|
|
if i == j {
|
|
|
|
assert_eq!(ni.cmp(nj), Equal);
|
|
|
|
assert_eq!(nj.cmp(ni), Equal);
|
|
|
|
assert_eq!(ni, nj);
|
|
|
|
assert!(!(ni != nj));
|
|
|
|
assert!(ni <= nj);
|
|
|
|
assert!(ni >= nj);
|
|
|
|
assert!(!(ni < nj));
|
|
|
|
assert!(!(ni > nj));
|
|
|
|
} else {
|
|
|
|
assert_eq!(ni.cmp(nj), Less);
|
|
|
|
assert_eq!(nj.cmp(ni), Greater);
|
|
|
|
|
|
|
|
assert!(!(ni == nj));
|
|
|
|
assert!(ni != nj);
|
|
|
|
|
|
|
|
assert!(ni <= nj);
|
|
|
|
assert!(!(ni >= nj));
|
|
|
|
assert!(ni < nj);
|
|
|
|
assert!(!(ni > nj));
|
|
|
|
|
|
|
|
assert!(!(nj <= ni));
|
|
|
|
assert!(nj >= ni);
|
|
|
|
assert!(!(nj < ni));
|
|
|
|
assert!(nj > ni);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_hash() {
|
|
|
|
let a = BigUint::new(vec!());
|
|
|
|
let b = BigUint::new(vec!(0));
|
|
|
|
let c = BigUint::new(vec!(1));
|
|
|
|
let d = BigUint::new(vec!(1,0,0,0,0,0));
|
|
|
|
let e = BigUint::new(vec!(0,0,0,0,0,1));
|
2015-01-09 11:36:03 +00:00
|
|
|
assert!(::hash(&a) == ::hash(&b));
|
|
|
|
assert!(::hash(&b) != ::hash(&c));
|
|
|
|
assert!(::hash(&c) == ::hash(&d));
|
|
|
|
assert!(::hash(&d) != ::hash(&e));
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
2015-11-16 19:06:39 +00:00
|
|
|
const BIT_TESTS: &'static [(&'static [BigDigit],
|
|
|
|
&'static [BigDigit],
|
|
|
|
&'static [BigDigit],
|
|
|
|
&'static [BigDigit],
|
|
|
|
&'static [BigDigit])] = &[
|
|
|
|
// LEFT RIGHT AND OR XOR
|
|
|
|
( &[], &[], &[], &[], &[] ),
|
|
|
|
( &[268, 482, 17], &[964, 54], &[260, 34], &[972, 502, 17], &[712, 468, 17] ),
|
|
|
|
];
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[test]
|
|
|
|
fn test_bitand() {
|
2015-11-16 19:06:39 +00:00
|
|
|
for elm in BIT_TESTS {
|
|
|
|
let (a_vec, b_vec, c_vec, _, _) = *elm;
|
|
|
|
let a = BigUint::from_slice(a_vec);
|
|
|
|
let b = BigUint::from_slice(b_vec);
|
|
|
|
let c = BigUint::from_slice(c_vec);
|
|
|
|
|
|
|
|
assert_op!(a & b == c);
|
|
|
|
assert_op!(b & a == c);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_bitor() {
|
2015-11-16 19:06:39 +00:00
|
|
|
for elm in BIT_TESTS {
|
|
|
|
let (a_vec, b_vec, _, c_vec, _) = *elm;
|
|
|
|
let a = BigUint::from_slice(a_vec);
|
|
|
|
let b = BigUint::from_slice(b_vec);
|
|
|
|
let c = BigUint::from_slice(c_vec);
|
|
|
|
|
|
|
|
assert_op!(a | b == c);
|
|
|
|
assert_op!(b | a == c);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_bitxor() {
|
2015-11-16 19:06:39 +00:00
|
|
|
for elm in BIT_TESTS {
|
|
|
|
let (a_vec, b_vec, _, _, c_vec) = *elm;
|
|
|
|
let a = BigUint::from_slice(a_vec);
|
|
|
|
let b = BigUint::from_slice(b_vec);
|
|
|
|
let c = BigUint::from_slice(c_vec);
|
|
|
|
|
|
|
|
assert_op!(a ^ b == c);
|
|
|
|
assert_op!(b ^ a == c);
|
|
|
|
assert_op!(a ^ c == b);
|
|
|
|
assert_op!(c ^ a == b);
|
|
|
|
assert_op!(b ^ c == a);
|
|
|
|
assert_op!(c ^ b == a);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_shl() {
|
2015-01-09 11:36:03 +00:00
|
|
|
fn check(s: &str, shift: usize, ans: &str) {
|
2015-04-03 06:29:17 +00:00
|
|
|
let opt_biguint = BigUint::from_str_radix(s, 16).ok();
|
2015-11-09 20:50:25 +00:00
|
|
|
let bu = (opt_biguint.unwrap() << shift).to_str_radix(16);
|
2015-03-29 17:05:02 +00:00
|
|
|
assert_eq!(bu, ans);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
check("0", 3, "0");
|
|
|
|
check("1", 3, "8");
|
|
|
|
|
|
|
|
check("1\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0001\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0001",
|
|
|
|
3,
|
|
|
|
"8\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0008\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0008");
|
|
|
|
check("1\
|
|
|
|
0000\
|
|
|
|
0001\
|
|
|
|
0000\
|
|
|
|
0001",
|
|
|
|
2,
|
|
|
|
"4\
|
|
|
|
0000\
|
|
|
|
0004\
|
|
|
|
0000\
|
|
|
|
0004");
|
|
|
|
check("1\
|
|
|
|
0001\
|
|
|
|
0001",
|
|
|
|
1,
|
|
|
|
"2\
|
|
|
|
0002\
|
|
|
|
0002");
|
|
|
|
|
|
|
|
check("\
|
|
|
|
4000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000",
|
|
|
|
3,
|
|
|
|
"2\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000");
|
|
|
|
check("4000\
|
|
|
|
0000",
|
|
|
|
2,
|
|
|
|
"1\
|
|
|
|
0000\
|
|
|
|
0000");
|
|
|
|
check("4000",
|
|
|
|
2,
|
|
|
|
"1\
|
|
|
|
0000");
|
|
|
|
|
|
|
|
check("4000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000",
|
|
|
|
67,
|
|
|
|
"2\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000");
|
|
|
|
check("4000\
|
|
|
|
0000",
|
|
|
|
35,
|
|
|
|
"2\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000");
|
|
|
|
check("4000",
|
|
|
|
19,
|
|
|
|
"2\
|
|
|
|
0000\
|
|
|
|
0000");
|
|
|
|
|
|
|
|
check("fedc\
|
|
|
|
ba98\
|
|
|
|
7654\
|
|
|
|
3210\
|
|
|
|
fedc\
|
|
|
|
ba98\
|
|
|
|
7654\
|
|
|
|
3210",
|
|
|
|
4,
|
|
|
|
"f\
|
|
|
|
edcb\
|
|
|
|
a987\
|
|
|
|
6543\
|
|
|
|
210f\
|
|
|
|
edcb\
|
|
|
|
a987\
|
|
|
|
6543\
|
|
|
|
2100");
|
|
|
|
check("88887777666655554444333322221111", 16,
|
|
|
|
"888877776666555544443333222211110000");
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_shr() {
|
2015-01-09 11:36:03 +00:00
|
|
|
fn check(s: &str, shift: usize, ans: &str) {
|
2015-04-03 06:29:17 +00:00
|
|
|
let opt_biguint = BigUint::from_str_radix(s, 16).ok();
|
2015-11-09 20:50:25 +00:00
|
|
|
let bu = (opt_biguint.unwrap() >> shift).to_str_radix(16);
|
2015-03-29 17:05:02 +00:00
|
|
|
assert_eq!(bu, ans);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
check("0", 3, "0");
|
|
|
|
check("f", 3, "1");
|
|
|
|
|
|
|
|
check("1\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0001\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0001",
|
|
|
|
3,
|
|
|
|
"2000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
2000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000");
|
|
|
|
check("1\
|
|
|
|
0000\
|
|
|
|
0001\
|
|
|
|
0000\
|
|
|
|
0001",
|
|
|
|
2,
|
|
|
|
"4000\
|
|
|
|
0000\
|
|
|
|
4000\
|
|
|
|
0000");
|
|
|
|
check("1\
|
|
|
|
0001\
|
|
|
|
0001",
|
|
|
|
1,
|
|
|
|
"8000\
|
|
|
|
8000");
|
|
|
|
|
|
|
|
check("2\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0001\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0001",
|
|
|
|
67,
|
|
|
|
"4000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000");
|
|
|
|
check("2\
|
|
|
|
0000\
|
|
|
|
0001\
|
|
|
|
0000\
|
|
|
|
0001",
|
|
|
|
35,
|
|
|
|
"4000\
|
|
|
|
0000");
|
|
|
|
check("2\
|
|
|
|
0001\
|
|
|
|
0001",
|
|
|
|
19,
|
|
|
|
"4000");
|
|
|
|
|
|
|
|
check("1\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000",
|
|
|
|
1,
|
|
|
|
"8000\
|
|
|
|
0000\
|
|
|
|
0000\
|
|
|
|
0000");
|
|
|
|
check("1\
|
|
|
|
0000\
|
|
|
|
0000",
|
|
|
|
1,
|
|
|
|
"8000\
|
|
|
|
0000");
|
|
|
|
check("1\
|
|
|
|
0000",
|
|
|
|
1,
|
|
|
|
"8000");
|
|
|
|
check("f\
|
|
|
|
edcb\
|
|
|
|
a987\
|
|
|
|
6543\
|
|
|
|
210f\
|
|
|
|
edcb\
|
|
|
|
a987\
|
|
|
|
6543\
|
|
|
|
2100",
|
|
|
|
4,
|
|
|
|
"fedc\
|
|
|
|
ba98\
|
|
|
|
7654\
|
|
|
|
3210\
|
|
|
|
fedc\
|
|
|
|
ba98\
|
|
|
|
7654\
|
|
|
|
3210");
|
|
|
|
|
|
|
|
check("888877776666555544443333222211110000", 16,
|
|
|
|
"88887777666655554444333322221111");
|
|
|
|
}
|
|
|
|
|
2015-04-03 06:29:17 +00:00
|
|
|
const N1: BigDigit = -1i32 as BigDigit;
|
|
|
|
const N2: BigDigit = -2i32 as BigDigit;
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
// `DoubleBigDigit` size dependent
|
|
|
|
#[test]
|
|
|
|
fn test_convert_i64() {
|
|
|
|
fn check(b1: BigUint, i: i64) {
|
|
|
|
let b2: BigUint = FromPrimitive::from_i64(i).unwrap();
|
|
|
|
assert!(b1 == b2);
|
|
|
|
assert!(b1.to_i64().unwrap() == i);
|
|
|
|
}
|
|
|
|
|
|
|
|
check(Zero::zero(), 0);
|
|
|
|
check(One::one(), 1);
|
2015-01-09 21:54:32 +00:00
|
|
|
check(i64::MAX.to_biguint().unwrap(), i64::MAX);
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
check(BigUint::new(vec!( )), 0);
|
2015-01-20 19:17:41 +00:00
|
|
|
check(BigUint::new(vec!( 1 )), (1 << (0*big_digit::BITS)));
|
2015-04-03 06:29:17 +00:00
|
|
|
check(BigUint::new(vec!(N1 )), (1 << (1*big_digit::BITS)) - 1);
|
2015-01-20 19:17:41 +00:00
|
|
|
check(BigUint::new(vec!( 0, 1 )), (1 << (1*big_digit::BITS)));
|
2015-04-03 06:29:17 +00:00
|
|
|
check(BigUint::new(vec!(N1, N1 >> 1)), i64::MAX);
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2015-01-09 21:54:32 +00:00
|
|
|
assert_eq!(i64::MIN.to_biguint(), None);
|
2015-04-03 06:29:17 +00:00
|
|
|
assert_eq!(BigUint::new(vec!(N1, N1 )).to_i64(), None);
|
2014-09-16 17:35:35 +00:00
|
|
|
assert_eq!(BigUint::new(vec!( 0, 0, 1)).to_i64(), None);
|
2015-04-03 06:29:17 +00:00
|
|
|
assert_eq!(BigUint::new(vec!(N1, N1, N1)).to_i64(), None);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// `DoubleBigDigit` size dependent
|
|
|
|
#[test]
|
|
|
|
fn test_convert_u64() {
|
|
|
|
fn check(b1: BigUint, u: u64) {
|
|
|
|
let b2: BigUint = FromPrimitive::from_u64(u).unwrap();
|
|
|
|
assert!(b1 == b2);
|
|
|
|
assert!(b1.to_u64().unwrap() == u);
|
|
|
|
}
|
|
|
|
|
|
|
|
check(Zero::zero(), 0);
|
|
|
|
check(One::one(), 1);
|
2015-01-09 21:54:32 +00:00
|
|
|
check(u64::MIN.to_biguint().unwrap(), u64::MIN);
|
|
|
|
check(u64::MAX.to_biguint().unwrap(), u64::MAX);
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
check(BigUint::new(vec!( )), 0);
|
2015-01-20 19:17:41 +00:00
|
|
|
check(BigUint::new(vec!( 1 )), (1 << (0*big_digit::BITS)));
|
2015-04-03 06:29:17 +00:00
|
|
|
check(BigUint::new(vec!(N1 )), (1 << (1*big_digit::BITS)) - 1);
|
2015-01-20 19:17:41 +00:00
|
|
|
check(BigUint::new(vec!( 0, 1)), (1 << (1*big_digit::BITS)));
|
2015-04-03 06:29:17 +00:00
|
|
|
check(BigUint::new(vec!(N1, N1)), u64::MAX);
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
assert_eq!(BigUint::new(vec!( 0, 0, 1)).to_u64(), None);
|
2015-04-03 06:29:17 +00:00
|
|
|
assert_eq!(BigUint::new(vec!(N1, N1, N1)).to_u64(), None);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_convert_to_bigint() {
|
|
|
|
fn check(n: BigUint, ans: BigInt) {
|
|
|
|
assert_eq!(n.to_bigint().unwrap(), ans);
|
2015-01-09 21:54:32 +00:00
|
|
|
assert_eq!(n.to_bigint().unwrap().to_biguint().unwrap(), n);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
check(Zero::zero(), Zero::zero());
|
|
|
|
check(BigUint::new(vec!(1,2,3)),
|
|
|
|
BigInt::from_biguint(Plus, BigUint::new(vec!(1,2,3))));
|
|
|
|
}
|
|
|
|
|
2014-10-10 13:54:30 +00:00
|
|
|
const SUM_TRIPLES: &'static [(&'static [BigDigit],
|
|
|
|
&'static [BigDigit],
|
|
|
|
&'static [BigDigit])] = &[
|
2014-09-16 17:35:35 +00:00
|
|
|
(&[], &[], &[]),
|
|
|
|
(&[], &[ 1], &[ 1]),
|
|
|
|
(&[ 1], &[ 1], &[ 2]),
|
|
|
|
(&[ 1], &[ 1, 1], &[ 2, 1]),
|
2015-04-03 06:29:17 +00:00
|
|
|
(&[ 1], &[N1], &[ 0, 1]),
|
|
|
|
(&[ 1], &[N1, N1], &[ 0, 0, 1]),
|
|
|
|
(&[N1, N1], &[N1, N1], &[N2, N1, 1]),
|
|
|
|
(&[ 1, 1, 1], &[N1, N1], &[ 0, 1, 2]),
|
|
|
|
(&[ 2, 2, 1], &[N1, N2], &[ 1, 1, 2])
|
2014-09-16 17:35:35 +00:00
|
|
|
];
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_add() {
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in SUM_TRIPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec) = *elm;
|
|
|
|
let a = BigUint::from_slice(a_vec);
|
|
|
|
let b = BigUint::from_slice(b_vec);
|
|
|
|
let c = BigUint::from_slice(c_vec);
|
|
|
|
|
2015-11-16 19:06:39 +00:00
|
|
|
assert_op!(a + b == c);
|
|
|
|
assert_op!(b + a == c);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_sub() {
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in SUM_TRIPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec) = *elm;
|
|
|
|
let a = BigUint::from_slice(a_vec);
|
|
|
|
let b = BigUint::from_slice(b_vec);
|
|
|
|
let c = BigUint::from_slice(c_vec);
|
|
|
|
|
2015-11-16 19:06:39 +00:00
|
|
|
assert_op!(c - a == b);
|
|
|
|
assert_op!(c - b == a);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2015-03-18 04:21:25 +00:00
|
|
|
#[should_panic]
|
2014-09-16 17:35:35 +00:00
|
|
|
fn test_sub_fail_on_underflow() {
|
|
|
|
let (a, b) : (BigUint, BigUint) = (Zero::zero(), One::one());
|
|
|
|
a - b;
|
|
|
|
}
|
|
|
|
|
2015-04-02 16:37:32 +00:00
|
|
|
const M: u32 = ::std::u32::MAX;
|
2014-10-10 13:54:30 +00:00
|
|
|
const MUL_TRIPLES: &'static [(&'static [BigDigit],
|
|
|
|
&'static [BigDigit],
|
|
|
|
&'static [BigDigit])] = &[
|
2014-09-16 17:35:35 +00:00
|
|
|
(&[], &[], &[]),
|
|
|
|
(&[], &[ 1], &[]),
|
|
|
|
(&[ 2], &[], &[]),
|
|
|
|
(&[ 1], &[ 1], &[1]),
|
|
|
|
(&[ 2], &[ 3], &[ 6]),
|
|
|
|
(&[ 1], &[ 1, 1, 1], &[1, 1, 1]),
|
|
|
|
(&[ 1, 2, 3], &[ 3], &[ 3, 6, 9]),
|
2015-04-03 06:29:17 +00:00
|
|
|
(&[ 1, 1, 1], &[N1], &[N1, N1, N1]),
|
|
|
|
(&[ 1, 2, 3], &[N1], &[N1, N2, N2, 2]),
|
|
|
|
(&[ 1, 2, 3, 4], &[N1], &[N1, N2, N2, N2, 3]),
|
|
|
|
(&[N1], &[N1], &[ 1, N2]),
|
|
|
|
(&[N1, N1], &[N1], &[ 1, N1, N2]),
|
|
|
|
(&[N1, N1, N1], &[N1], &[ 1, N1, N1, N2]),
|
|
|
|
(&[N1, N1, N1, N1], &[N1], &[ 1, N1, N1, N1, N2]),
|
2015-04-02 16:37:32 +00:00
|
|
|
(&[ M/2 + 1], &[ 2], &[ 0, 1]),
|
|
|
|
(&[0, M/2 + 1], &[ 2], &[ 0, 0, 1]),
|
2014-09-16 17:35:35 +00:00
|
|
|
(&[ 1, 2], &[ 1, 2, 3], &[1, 4, 7, 6]),
|
2015-04-03 06:29:17 +00:00
|
|
|
(&[N1, N1], &[N1, N1, N1], &[1, 0, N1, N2, N1]),
|
|
|
|
(&[N1, N1, N1], &[N1, N1, N1, N1], &[1, 0, 0, N1, N2, N1, N1]),
|
2014-09-16 17:35:35 +00:00
|
|
|
(&[ 0, 0, 1], &[ 1, 2, 3], &[0, 0, 1, 2, 3]),
|
|
|
|
(&[ 0, 0, 1], &[ 0, 0, 0, 1], &[0, 0, 0, 0, 0, 1])
|
|
|
|
];
|
|
|
|
|
2014-10-10 13:54:30 +00:00
|
|
|
const DIV_REM_QUADRUPLES: &'static [(&'static [BigDigit],
|
|
|
|
&'static [BigDigit],
|
|
|
|
&'static [BigDigit],
|
|
|
|
&'static [BigDigit])]
|
2014-09-16 17:35:35 +00:00
|
|
|
= &[
|
|
|
|
(&[ 1], &[ 2], &[], &[1]),
|
2015-04-02 16:37:32 +00:00
|
|
|
(&[ 1, 1], &[ 2], &[ M/2+1], &[1]),
|
|
|
|
(&[ 1, 1, 1], &[ 2], &[ M/2+1, M/2+1], &[1]),
|
2015-04-03 06:29:17 +00:00
|
|
|
(&[ 0, 1], &[N1], &[1], &[1]),
|
|
|
|
(&[N1, N1], &[N2], &[2, 1], &[3])
|
2014-09-16 17:35:35 +00:00
|
|
|
];
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_mul() {
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in MUL_TRIPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec) = *elm;
|
|
|
|
let a = BigUint::from_slice(a_vec);
|
|
|
|
let b = BigUint::from_slice(b_vec);
|
|
|
|
let c = BigUint::from_slice(c_vec);
|
|
|
|
|
2015-11-16 19:06:39 +00:00
|
|
|
assert_op!(a * b == c);
|
|
|
|
assert_op!(b * a == c);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in DIV_REM_QUADRUPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec, d_vec) = *elm;
|
|
|
|
let a = BigUint::from_slice(a_vec);
|
|
|
|
let b = BigUint::from_slice(b_vec);
|
|
|
|
let c = BigUint::from_slice(c_vec);
|
|
|
|
let d = BigUint::from_slice(d_vec);
|
|
|
|
|
2014-12-16 14:38:35 +00:00
|
|
|
assert!(a == &b * &c + &d);
|
|
|
|
assert!(a == &c * &b + &d);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_div_rem() {
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in MUL_TRIPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec) = *elm;
|
|
|
|
let a = BigUint::from_slice(a_vec);
|
|
|
|
let b = BigUint::from_slice(b_vec);
|
|
|
|
let c = BigUint::from_slice(c_vec);
|
|
|
|
|
|
|
|
if !a.is_zero() {
|
2015-11-16 19:06:39 +00:00
|
|
|
assert_op!(c / a == b);
|
|
|
|
assert_op!(c % a == Zero::zero());
|
2014-09-16 17:35:35 +00:00
|
|
|
assert_eq!(c.div_rem(&a), (b.clone(), Zero::zero()));
|
|
|
|
}
|
|
|
|
if !b.is_zero() {
|
2015-11-16 19:06:39 +00:00
|
|
|
assert_op!(c / b == a);
|
|
|
|
assert_op!(c % b == Zero::zero());
|
2014-09-16 17:35:35 +00:00
|
|
|
assert_eq!(c.div_rem(&b), (a.clone(), Zero::zero()));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in DIV_REM_QUADRUPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec, d_vec) = *elm;
|
|
|
|
let a = BigUint::from_slice(a_vec);
|
|
|
|
let b = BigUint::from_slice(b_vec);
|
|
|
|
let c = BigUint::from_slice(c_vec);
|
|
|
|
let d = BigUint::from_slice(d_vec);
|
|
|
|
|
2015-11-16 19:06:39 +00:00
|
|
|
if !b.is_zero() {
|
|
|
|
assert_op!(a / b == c);
|
|
|
|
assert_op!(a % b == d);
|
|
|
|
assert!(a.div_rem(&b) == (c, d));
|
|
|
|
}
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_checked_add() {
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in SUM_TRIPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec) = *elm;
|
|
|
|
let a = BigUint::from_slice(a_vec);
|
|
|
|
let b = BigUint::from_slice(b_vec);
|
|
|
|
let c = BigUint::from_slice(c_vec);
|
|
|
|
|
|
|
|
assert!(a.checked_add(&b).unwrap() == c);
|
|
|
|
assert!(b.checked_add(&a).unwrap() == c);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_checked_sub() {
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in SUM_TRIPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec) = *elm;
|
|
|
|
let a = BigUint::from_slice(a_vec);
|
|
|
|
let b = BigUint::from_slice(b_vec);
|
|
|
|
let c = BigUint::from_slice(c_vec);
|
|
|
|
|
|
|
|
assert!(c.checked_sub(&a).unwrap() == b);
|
|
|
|
assert!(c.checked_sub(&b).unwrap() == a);
|
|
|
|
|
|
|
|
if a > c {
|
|
|
|
assert!(a.checked_sub(&c).is_none());
|
|
|
|
}
|
|
|
|
if b > c {
|
|
|
|
assert!(b.checked_sub(&c).is_none());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_checked_mul() {
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in MUL_TRIPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec) = *elm;
|
|
|
|
let a = BigUint::from_slice(a_vec);
|
|
|
|
let b = BigUint::from_slice(b_vec);
|
|
|
|
let c = BigUint::from_slice(c_vec);
|
|
|
|
|
|
|
|
assert!(a.checked_mul(&b).unwrap() == c);
|
|
|
|
assert!(b.checked_mul(&a).unwrap() == c);
|
|
|
|
}
|
|
|
|
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in DIV_REM_QUADRUPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec, d_vec) = *elm;
|
|
|
|
let a = BigUint::from_slice(a_vec);
|
|
|
|
let b = BigUint::from_slice(b_vec);
|
|
|
|
let c = BigUint::from_slice(c_vec);
|
|
|
|
let d = BigUint::from_slice(d_vec);
|
|
|
|
|
2014-12-16 14:38:35 +00:00
|
|
|
assert!(a == b.checked_mul(&c).unwrap() + &d);
|
|
|
|
assert!(a == c.checked_mul(&b).unwrap() + &d);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_checked_div() {
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in MUL_TRIPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec) = *elm;
|
|
|
|
let a = BigUint::from_slice(a_vec);
|
|
|
|
let b = BigUint::from_slice(b_vec);
|
|
|
|
let c = BigUint::from_slice(c_vec);
|
|
|
|
|
|
|
|
if !a.is_zero() {
|
|
|
|
assert!(c.checked_div(&a).unwrap() == b);
|
|
|
|
}
|
|
|
|
if !b.is_zero() {
|
|
|
|
assert!(c.checked_div(&b).unwrap() == a);
|
|
|
|
}
|
|
|
|
|
|
|
|
assert!(c.checked_div(&Zero::zero()).is_none());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_gcd() {
|
2015-01-09 11:36:03 +00:00
|
|
|
fn check(a: usize, b: usize, c: usize) {
|
2015-03-04 17:45:19 +00:00
|
|
|
let big_a: BigUint = FromPrimitive::from_usize(a).unwrap();
|
|
|
|
let big_b: BigUint = FromPrimitive::from_usize(b).unwrap();
|
|
|
|
let big_c: BigUint = FromPrimitive::from_usize(c).unwrap();
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
assert_eq!(big_a.gcd(&big_b), big_c);
|
|
|
|
}
|
|
|
|
|
|
|
|
check(10, 2, 2);
|
|
|
|
check(10, 3, 1);
|
|
|
|
check(0, 3, 3);
|
|
|
|
check(3, 3, 3);
|
|
|
|
check(56, 42, 14);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_lcm() {
|
2015-01-09 11:36:03 +00:00
|
|
|
fn check(a: usize, b: usize, c: usize) {
|
2015-03-04 17:45:19 +00:00
|
|
|
let big_a: BigUint = FromPrimitive::from_usize(a).unwrap();
|
|
|
|
let big_b: BigUint = FromPrimitive::from_usize(b).unwrap();
|
|
|
|
let big_c: BigUint = FromPrimitive::from_usize(c).unwrap();
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
assert_eq!(big_a.lcm(&big_b), big_c);
|
|
|
|
}
|
|
|
|
|
|
|
|
check(1, 0, 0);
|
|
|
|
check(0, 1, 0);
|
|
|
|
check(1, 1, 1);
|
|
|
|
check(8, 9, 72);
|
|
|
|
check(11, 5, 55);
|
|
|
|
check(99, 17, 1683);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_is_even() {
|
|
|
|
let one: BigUint = FromStr::from_str("1").unwrap();
|
|
|
|
let two: BigUint = FromStr::from_str("2").unwrap();
|
|
|
|
let thousand: BigUint = FromStr::from_str("1000").unwrap();
|
|
|
|
let big: BigUint = FromStr::from_str("1000000000000000000000").unwrap();
|
|
|
|
let bigger: BigUint = FromStr::from_str("1000000000000000000001").unwrap();
|
|
|
|
assert!(one.is_odd());
|
|
|
|
assert!(two.is_even());
|
|
|
|
assert!(thousand.is_even());
|
|
|
|
assert!(big.is_even());
|
|
|
|
assert!(bigger.is_odd());
|
2014-12-16 14:38:35 +00:00
|
|
|
assert!((&one << 64).is_even());
|
|
|
|
assert!(((&one << 64) + one).is_odd());
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
2015-02-19 01:46:43 +00:00
|
|
|
fn to_str_pairs() -> Vec<(BigUint, Vec<(u32, String)>)> {
|
2015-01-20 19:17:41 +00:00
|
|
|
let bits = big_digit::BITS;
|
2014-09-16 17:35:35 +00:00
|
|
|
vec!(( Zero::zero(), vec!(
|
|
|
|
(2, "0".to_string()), (3, "0".to_string())
|
2014-11-20 20:21:06 +00:00
|
|
|
)), ( BigUint::from_slice(&[ 0xff ]), vec!(
|
2014-09-16 17:35:35 +00:00
|
|
|
(2, "11111111".to_string()),
|
|
|
|
(3, "100110".to_string()),
|
|
|
|
(4, "3333".to_string()),
|
|
|
|
(5, "2010".to_string()),
|
|
|
|
(6, "1103".to_string()),
|
|
|
|
(7, "513".to_string()),
|
|
|
|
(8, "377".to_string()),
|
|
|
|
(9, "313".to_string()),
|
|
|
|
(10, "255".to_string()),
|
|
|
|
(11, "212".to_string()),
|
|
|
|
(12, "193".to_string()),
|
|
|
|
(13, "168".to_string()),
|
|
|
|
(14, "143".to_string()),
|
|
|
|
(15, "120".to_string()),
|
|
|
|
(16, "ff".to_string())
|
2014-11-20 20:21:06 +00:00
|
|
|
)), ( BigUint::from_slice(&[ 0xfff ]), vec!(
|
2014-09-16 17:35:35 +00:00
|
|
|
(2, "111111111111".to_string()),
|
|
|
|
(4, "333333".to_string()),
|
|
|
|
(16, "fff".to_string())
|
2014-11-20 20:21:06 +00:00
|
|
|
)), ( BigUint::from_slice(&[ 1, 2 ]), vec!(
|
2014-09-16 17:35:35 +00:00
|
|
|
(2,
|
2014-12-23 17:50:53 +00:00
|
|
|
format!("10{}1", repeat("0").take(bits - 1).collect::<String>())),
|
2014-09-16 17:35:35 +00:00
|
|
|
(4,
|
2014-12-23 17:50:53 +00:00
|
|
|
format!("2{}1", repeat("0").take(bits / 2 - 1).collect::<String>())),
|
2014-09-16 17:35:35 +00:00
|
|
|
(10, match bits {
|
|
|
|
32 => "8589934593".to_string(),
|
|
|
|
16 => "131073".to_string(),
|
2014-10-30 13:20:15 +00:00
|
|
|
_ => panic!()
|
2014-09-16 17:35:35 +00:00
|
|
|
}),
|
|
|
|
(16,
|
2014-12-23 17:50:53 +00:00
|
|
|
format!("2{}1", repeat("0").take(bits / 4 - 1).collect::<String>()))
|
2014-11-20 20:21:06 +00:00
|
|
|
)), ( BigUint::from_slice(&[ 1, 2, 3 ]), vec!(
|
2014-09-16 17:35:35 +00:00
|
|
|
(2,
|
|
|
|
format!("11{}10{}1",
|
2014-12-23 17:50:53 +00:00
|
|
|
repeat("0").take(bits - 2).collect::<String>(),
|
|
|
|
repeat("0").take(bits - 1).collect::<String>())),
|
2014-09-16 17:35:35 +00:00
|
|
|
(4,
|
|
|
|
format!("3{}2{}1",
|
2014-12-23 17:50:53 +00:00
|
|
|
repeat("0").take(bits / 2 - 1).collect::<String>(),
|
|
|
|
repeat("0").take(bits / 2 - 1).collect::<String>())),
|
2014-09-16 17:35:35 +00:00
|
|
|
(10, match bits {
|
|
|
|
32 => "55340232229718589441".to_string(),
|
|
|
|
16 => "12885032961".to_string(),
|
2014-10-30 13:20:15 +00:00
|
|
|
_ => panic!()
|
2014-09-16 17:35:35 +00:00
|
|
|
}),
|
|
|
|
(16,
|
|
|
|
format!("3{}2{}1",
|
2014-12-23 17:50:53 +00:00
|
|
|
repeat("0").take(bits / 4 - 1).collect::<String>(),
|
|
|
|
repeat("0").take(bits / 4 - 1).collect::<String>()))
|
2014-09-16 17:35:35 +00:00
|
|
|
)) )
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_to_str_radix() {
|
|
|
|
let r = to_str_pairs();
|
|
|
|
for num_pair in r.iter() {
|
|
|
|
let &(ref n, ref rs) = num_pair;
|
|
|
|
for str_pair in rs.iter() {
|
|
|
|
let &(ref radix, ref str) = str_pair;
|
2015-11-09 20:50:25 +00:00
|
|
|
assert_eq!(n.to_str_radix(*radix), *str);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_from_str_radix() {
|
|
|
|
let r = to_str_pairs();
|
|
|
|
for num_pair in r.iter() {
|
|
|
|
let &(ref n, ref rs) = num_pair;
|
|
|
|
for str_pair in rs.iter() {
|
|
|
|
let &(ref radix, ref str) = str_pair;
|
|
|
|
assert_eq!(n,
|
2015-04-03 06:29:17 +00:00
|
|
|
&BigUint::from_str_radix(str, *radix).unwrap());
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-04-03 06:29:17 +00:00
|
|
|
let zed = BigUint::from_str_radix("Z", 10).ok();
|
2014-09-16 17:35:35 +00:00
|
|
|
assert_eq!(zed, None);
|
2015-04-03 06:29:17 +00:00
|
|
|
let blank = BigUint::from_str_radix("_", 2).ok();
|
2014-09-16 17:35:35 +00:00
|
|
|
assert_eq!(blank, None);
|
2015-04-03 06:29:17 +00:00
|
|
|
let minus_one = BigUint::from_str_radix("-1", 10).ok();
|
2014-09-16 17:35:35 +00:00
|
|
|
assert_eq!(minus_one, None);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_factor() {
|
2015-01-09 11:36:03 +00:00
|
|
|
fn factor(n: usize) -> BigUint {
|
2014-09-16 17:35:35 +00:00
|
|
|
let mut f: BigUint = One::one();
|
2015-03-19 16:57:18 +00:00
|
|
|
for i in 2..n + 1 {
|
2014-09-16 17:35:35 +00:00
|
|
|
// FIXME(#5992): assignment operator overloads
|
2015-03-04 17:45:19 +00:00
|
|
|
// f *= FromPrimitive::from_usize(i);
|
|
|
|
let bu: BigUint = FromPrimitive::from_usize(i).unwrap();
|
2014-12-16 14:38:35 +00:00
|
|
|
f = f * bu;
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
return f;
|
|
|
|
}
|
|
|
|
|
2015-01-09 11:36:03 +00:00
|
|
|
fn check(n: usize, s: &str) {
|
2014-09-16 17:35:35 +00:00
|
|
|
let n = factor(n);
|
2015-04-03 06:29:17 +00:00
|
|
|
let ans = match BigUint::from_str_radix(s, 10) {
|
2015-02-03 19:42:46 +00:00
|
|
|
Ok(x) => x, Err(_) => panic!()
|
2014-09-16 17:35:35 +00:00
|
|
|
};
|
|
|
|
assert_eq!(n, ans);
|
|
|
|
}
|
|
|
|
|
|
|
|
check(3, "6");
|
|
|
|
check(10, "3628800");
|
|
|
|
check(20, "2432902008176640000");
|
|
|
|
check(30, "265252859812191058636308480000000");
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_bits() {
|
|
|
|
assert_eq!(BigUint::new(vec!(0,0,0,0)).bits(), 0);
|
2015-03-04 17:45:19 +00:00
|
|
|
let n: BigUint = FromPrimitive::from_usize(0).unwrap();
|
2014-09-16 17:35:35 +00:00
|
|
|
assert_eq!(n.bits(), 0);
|
2015-03-04 17:45:19 +00:00
|
|
|
let n: BigUint = FromPrimitive::from_usize(1).unwrap();
|
2014-09-16 17:35:35 +00:00
|
|
|
assert_eq!(n.bits(), 1);
|
2015-03-04 17:45:19 +00:00
|
|
|
let n: BigUint = FromPrimitive::from_usize(3).unwrap();
|
2014-09-16 17:35:35 +00:00
|
|
|
assert_eq!(n.bits(), 2);
|
2015-04-03 06:29:17 +00:00
|
|
|
let n: BigUint = BigUint::from_str_radix("4000000000", 16).unwrap();
|
2014-09-16 17:35:35 +00:00
|
|
|
assert_eq!(n.bits(), 39);
|
|
|
|
let one: BigUint = One::one();
|
|
|
|
assert_eq!((one << 426).bits(), 427);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_rand() {
|
2015-01-01 17:07:52 +00:00
|
|
|
let mut rng = thread_rng();
|
2015-01-09 21:54:32 +00:00
|
|
|
let _n: BigUint = rng.gen_biguint(137);
|
|
|
|
assert!(rng.gen_biguint(0).is_zero());
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_rand_range() {
|
2015-01-01 17:07:52 +00:00
|
|
|
let mut rng = thread_rng();
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2015-03-19 16:57:18 +00:00
|
|
|
for _ in 0..10 {
|
2015-03-04 17:45:19 +00:00
|
|
|
assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_usize(236).unwrap(),
|
|
|
|
&FromPrimitive::from_usize(237).unwrap()),
|
|
|
|
FromPrimitive::from_usize(236).unwrap());
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
2015-03-04 17:45:19 +00:00
|
|
|
let l = FromPrimitive::from_usize(403469000 + 2352).unwrap();
|
|
|
|
let u = FromPrimitive::from_usize(403469000 + 3513).unwrap();
|
2015-03-19 16:57:18 +00:00
|
|
|
for _ in 0..1000 {
|
2015-01-09 21:54:32 +00:00
|
|
|
let n: BigUint = rng.gen_biguint_below(&u);
|
2014-09-16 17:35:35 +00:00
|
|
|
assert!(n < u);
|
|
|
|
|
2015-01-09 21:54:32 +00:00
|
|
|
let n: BigUint = rng.gen_biguint_range(&l, &u);
|
2014-09-16 17:35:35 +00:00
|
|
|
assert!(n >= l);
|
|
|
|
assert!(n < u);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2015-03-18 04:21:25 +00:00
|
|
|
#[should_panic]
|
2014-09-16 17:35:35 +00:00
|
|
|
fn test_zero_rand_range() {
|
2015-03-04 17:45:19 +00:00
|
|
|
thread_rng().gen_biguint_range(&FromPrimitive::from_usize(54).unwrap(),
|
|
|
|
&FromPrimitive::from_usize(54).unwrap());
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2015-03-18 04:21:25 +00:00
|
|
|
#[should_panic]
|
2014-09-16 17:35:35 +00:00
|
|
|
fn test_negative_rand_range() {
|
2015-01-01 17:07:52 +00:00
|
|
|
let mut rng = thread_rng();
|
2015-03-04 17:45:19 +00:00
|
|
|
let l = FromPrimitive::from_usize(2352).unwrap();
|
|
|
|
let u = FromPrimitive::from_usize(3513).unwrap();
|
2014-09-16 17:35:35 +00:00
|
|
|
// Switching u and l should fail:
|
2015-01-09 21:54:32 +00:00
|
|
|
let _n: BigUint = rng.gen_biguint_range(&u, &l);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
Improve multiply performance
The main idea here is to do as much as possible with slices, instead of
allocating new BigUints (= heap allocations).
Current performance:
multiply_0: 10,507 ns/iter (+/- 987)
multiply_1: 2,788,734 ns/iter (+/- 100,079)
multiply_2: 69,923,515 ns/iter (+/- 4,550,902)
After this patch, we get:
multiply_0: 364 ns/iter (+/- 62)
multiply_1: 34,085 ns/iter (+/- 1,179)
multiply_2: 3,753,883 ns/iter (+/- 46,876)
2015-12-11 00:25:42 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_sub_sign() {
|
|
|
|
use super::sub_sign;
|
|
|
|
let a = BigInt::from_str_radix("265252859812191058636308480000000", 10).unwrap();
|
|
|
|
let b = BigInt::from_str_radix("26525285981219105863630848000000", 10).unwrap();
|
|
|
|
|
|
|
|
assert_eq!(sub_sign(&a.data.data[..], &b.data.data[..]), &a - &b);
|
|
|
|
assert_eq!(sub_sign(&b.data.data[..], &a.data.data[..]), &b - &a);
|
|
|
|
}
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod bigint_tests {
|
|
|
|
use Integer;
|
|
|
|
use super::{BigDigit, BigUint, ToBigUint};
|
2015-01-20 19:17:41 +00:00
|
|
|
use super::{Sign, BigInt, RandBigInt, ToBigInt, big_digit};
|
2014-11-18 12:09:53 +00:00
|
|
|
use super::Sign::{Minus, NoSign, Plus};
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2014-12-23 16:12:57 +00:00
|
|
|
use std::cmp::Ordering::{Less, Equal, Greater};
|
2014-09-16 17:35:35 +00:00
|
|
|
use std::i64;
|
2014-12-23 17:50:53 +00:00
|
|
|
use std::iter::repeat;
|
2014-09-16 17:35:35 +00:00
|
|
|
use std::u64;
|
2015-01-03 18:30:05 +00:00
|
|
|
use std::ops::{Neg};
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2015-02-05 16:20:16 +00:00
|
|
|
use rand::thread_rng;
|
|
|
|
|
2015-04-03 06:29:17 +00:00
|
|
|
use {Zero, One, Signed, ToPrimitive, FromPrimitive, Num};
|
2014-11-15 03:30:48 +00:00
|
|
|
|
2015-11-16 19:06:39 +00:00
|
|
|
/// Assert that an op works for all val/ref combinations
|
|
|
|
macro_rules! assert_op {
|
|
|
|
($left:ident $op:tt $right:ident == $expected:expr) => {
|
|
|
|
assert_eq!((&$left) $op (&$right), $expected);
|
|
|
|
assert_eq!((&$left) $op $right.clone(), $expected);
|
|
|
|
assert_eq!($left.clone() $op (&$right), $expected);
|
|
|
|
assert_eq!($left.clone() $op $right.clone(), $expected);
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[test]
|
|
|
|
fn test_from_biguint() {
|
2015-01-09 11:36:03 +00:00
|
|
|
fn check(inp_s: Sign, inp_n: usize, ans_s: Sign, ans_n: usize) {
|
2015-03-04 17:45:19 +00:00
|
|
|
let inp = BigInt::from_biguint(inp_s, FromPrimitive::from_usize(inp_n).unwrap());
|
|
|
|
let ans = BigInt { sign: ans_s, data: FromPrimitive::from_usize(ans_n).unwrap()};
|
2014-09-16 17:35:35 +00:00
|
|
|
assert_eq!(inp, ans);
|
|
|
|
}
|
|
|
|
check(Plus, 1, Plus, 1);
|
2014-09-21 00:58:59 +00:00
|
|
|
check(Plus, 0, NoSign, 0);
|
2014-09-16 17:35:35 +00:00
|
|
|
check(Minus, 1, Minus, 1);
|
2014-09-21 00:58:59 +00:00
|
|
|
check(NoSign, 1, NoSign, 0);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
2015-01-21 01:38:51 +00:00
|
|
|
#[test]
|
|
|
|
fn test_from_bytes_be() {
|
|
|
|
fn check(s: &str, result: &str) {
|
|
|
|
assert_eq!(BigInt::from_bytes_be(Plus, s.as_bytes()),
|
|
|
|
BigInt::parse_bytes(result.as_bytes(), 10).unwrap());
|
|
|
|
}
|
|
|
|
check("A", "65");
|
|
|
|
check("AA", "16705");
|
|
|
|
check("AB", "16706");
|
|
|
|
check("Hello world!", "22405534230753963835153736737");
|
|
|
|
assert_eq!(BigInt::from_bytes_be(Plus, &[]), Zero::zero());
|
|
|
|
assert_eq!(BigInt::from_bytes_be(Minus, &[]), Zero::zero());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_to_bytes_be() {
|
|
|
|
fn check(s: &str, result: &str) {
|
|
|
|
let b = BigInt::parse_bytes(result.as_bytes(), 10).unwrap();
|
|
|
|
let (sign, v) = b.to_bytes_be();
|
|
|
|
assert_eq!((Plus, s.as_bytes()), (sign, &*v));
|
|
|
|
}
|
|
|
|
check("A", "65");
|
|
|
|
check("AA", "16705");
|
|
|
|
check("AB", "16706");
|
|
|
|
check("Hello world!", "22405534230753963835153736737");
|
|
|
|
let b: BigInt = Zero::zero();
|
|
|
|
assert_eq!(b.to_bytes_be(), (NoSign, vec![0]));
|
|
|
|
|
|
|
|
// Test with leading/trailing zero bytes and a full BigDigit of value 0
|
2015-04-03 06:29:17 +00:00
|
|
|
let b = BigInt::from_str_radix("00010000000000000200", 16).unwrap();
|
2015-01-21 01:38:51 +00:00
|
|
|
assert_eq!(b.to_bytes_be(), (Plus, vec![1, 0, 0, 0, 0, 0, 0, 2, 0]));
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_from_bytes_le() {
|
|
|
|
fn check(s: &str, result: &str) {
|
|
|
|
assert_eq!(BigInt::from_bytes_le(Plus, s.as_bytes()),
|
|
|
|
BigInt::parse_bytes(result.as_bytes(), 10).unwrap());
|
|
|
|
}
|
|
|
|
check("A", "65");
|
|
|
|
check("AA", "16705");
|
|
|
|
check("BA", "16706");
|
|
|
|
check("!dlrow olleH", "22405534230753963835153736737");
|
|
|
|
assert_eq!(BigInt::from_bytes_le(Plus, &[]), Zero::zero());
|
|
|
|
assert_eq!(BigInt::from_bytes_le(Minus, &[]), Zero::zero());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_to_bytes_le() {
|
|
|
|
fn check(s: &str, result: &str) {
|
|
|
|
let b = BigInt::parse_bytes(result.as_bytes(), 10).unwrap();
|
|
|
|
let (sign, v) = b.to_bytes_le();
|
|
|
|
assert_eq!((Plus, s.as_bytes()), (sign, &*v));
|
|
|
|
}
|
|
|
|
check("A", "65");
|
|
|
|
check("AA", "16705");
|
|
|
|
check("BA", "16706");
|
|
|
|
check("!dlrow olleH", "22405534230753963835153736737");
|
|
|
|
let b: BigInt = Zero::zero();
|
|
|
|
assert_eq!(b.to_bytes_le(), (NoSign, vec![0]));
|
|
|
|
|
|
|
|
// Test with leading/trailing zero bytes and a full BigDigit of value 0
|
2015-04-03 06:29:17 +00:00
|
|
|
let b = BigInt::from_str_radix("00010000000000000200", 16).unwrap();
|
2015-01-21 01:38:51 +00:00
|
|
|
assert_eq!(b.to_bytes_le(), (Plus, vec![0, 2, 0, 0, 0, 0, 0, 0, 1]));
|
|
|
|
}
|
|
|
|
|
2014-09-16 17:35:35 +00:00
|
|
|
#[test]
|
|
|
|
fn test_cmp() {
|
2015-01-03 18:30:05 +00:00
|
|
|
let vs: [&[BigDigit]; 4] = [ &[2 as BigDigit], &[1, 1], &[2, 1], &[1, 1, 1] ];
|
2014-09-16 17:35:35 +00:00
|
|
|
let mut nums = Vec::new();
|
|
|
|
for s in vs.iter().rev() {
|
|
|
|
nums.push(BigInt::from_slice(Minus, *s));
|
|
|
|
}
|
|
|
|
nums.push(Zero::zero());
|
|
|
|
nums.extend(vs.iter().map(|s| BigInt::from_slice(Plus, *s)));
|
|
|
|
|
|
|
|
for (i, ni) in nums.iter().enumerate() {
|
2015-01-23 16:54:55 +00:00
|
|
|
for (j0, nj) in nums[i..].iter().enumerate() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let j = i + j0;
|
|
|
|
if i == j {
|
|
|
|
assert_eq!(ni.cmp(nj), Equal);
|
|
|
|
assert_eq!(nj.cmp(ni), Equal);
|
|
|
|
assert_eq!(ni, nj);
|
|
|
|
assert!(!(ni != nj));
|
|
|
|
assert!(ni <= nj);
|
|
|
|
assert!(ni >= nj);
|
|
|
|
assert!(!(ni < nj));
|
|
|
|
assert!(!(ni > nj));
|
|
|
|
} else {
|
|
|
|
assert_eq!(ni.cmp(nj), Less);
|
|
|
|
assert_eq!(nj.cmp(ni), Greater);
|
|
|
|
|
|
|
|
assert!(!(ni == nj));
|
|
|
|
assert!(ni != nj);
|
|
|
|
|
|
|
|
assert!(ni <= nj);
|
|
|
|
assert!(!(ni >= nj));
|
|
|
|
assert!(ni < nj);
|
|
|
|
assert!(!(ni > nj));
|
|
|
|
|
|
|
|
assert!(!(nj <= ni));
|
|
|
|
assert!(nj >= ni);
|
|
|
|
assert!(!(nj < ni));
|
|
|
|
assert!(nj > ni);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_hash() {
|
2014-09-21 00:58:59 +00:00
|
|
|
let a = BigInt::new(NoSign, vec!());
|
|
|
|
let b = BigInt::new(NoSign, vec!(0));
|
2014-09-16 17:35:35 +00:00
|
|
|
let c = BigInt::new(Plus, vec!(1));
|
|
|
|
let d = BigInt::new(Plus, vec!(1,0,0,0,0,0));
|
|
|
|
let e = BigInt::new(Plus, vec!(0,0,0,0,0,1));
|
|
|
|
let f = BigInt::new(Minus, vec!(1));
|
2015-01-09 11:36:03 +00:00
|
|
|
assert!(::hash(&a) == ::hash(&b));
|
|
|
|
assert!(::hash(&b) != ::hash(&c));
|
|
|
|
assert!(::hash(&c) == ::hash(&d));
|
|
|
|
assert!(::hash(&d) != ::hash(&e));
|
|
|
|
assert!(::hash(&c) != ::hash(&f));
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_convert_i64() {
|
|
|
|
fn check(b1: BigInt, i: i64) {
|
|
|
|
let b2: BigInt = FromPrimitive::from_i64(i).unwrap();
|
|
|
|
assert!(b1 == b2);
|
|
|
|
assert!(b1.to_i64().unwrap() == i);
|
|
|
|
}
|
|
|
|
|
|
|
|
check(Zero::zero(), 0);
|
|
|
|
check(One::one(), 1);
|
|
|
|
check(i64::MIN.to_bigint().unwrap(), i64::MIN);
|
|
|
|
check(i64::MAX.to_bigint().unwrap(), i64::MAX);
|
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
(i64::MAX as u64 + 1).to_bigint().unwrap().to_i64(),
|
|
|
|
None);
|
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
BigInt::from_biguint(Plus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_i64(),
|
|
|
|
None);
|
|
|
|
|
|
|
|
assert_eq!(
|
2015-01-20 19:17:41 +00:00
|
|
|
BigInt::from_biguint(Minus, BigUint::new(vec!(1,0,0,1<<(big_digit::BITS-1)))).to_i64(),
|
2014-09-16 17:35:35 +00:00
|
|
|
None);
|
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
BigInt::from_biguint(Minus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_i64(),
|
|
|
|
None);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_convert_u64() {
|
|
|
|
fn check(b1: BigInt, u: u64) {
|
|
|
|
let b2: BigInt = FromPrimitive::from_u64(u).unwrap();
|
|
|
|
assert!(b1 == b2);
|
|
|
|
assert!(b1.to_u64().unwrap() == u);
|
|
|
|
}
|
|
|
|
|
|
|
|
check(Zero::zero(), 0);
|
|
|
|
check(One::one(), 1);
|
|
|
|
check(u64::MIN.to_bigint().unwrap(), u64::MIN);
|
|
|
|
check(u64::MAX.to_bigint().unwrap(), u64::MAX);
|
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
BigInt::from_biguint(Plus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_u64(),
|
|
|
|
None);
|
|
|
|
|
|
|
|
let max_value: BigUint = FromPrimitive::from_u64(u64::MAX).unwrap();
|
|
|
|
assert_eq!(BigInt::from_biguint(Minus, max_value).to_u64(), None);
|
|
|
|
assert_eq!(BigInt::from_biguint(Minus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_u64(), None);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2015-01-09 21:54:32 +00:00
|
|
|
fn test_convert_to_biguint() {
|
2014-09-16 17:35:35 +00:00
|
|
|
fn check(n: BigInt, ans_1: BigUint) {
|
2015-01-09 21:54:32 +00:00
|
|
|
assert_eq!(n.to_biguint().unwrap(), ans_1);
|
|
|
|
assert_eq!(n.to_biguint().unwrap().to_bigint().unwrap(), n);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
let zero: BigInt = Zero::zero();
|
|
|
|
let unsigned_zero: BigUint = Zero::zero();
|
|
|
|
let positive = BigInt::from_biguint(
|
|
|
|
Plus, BigUint::new(vec!(1,2,3)));
|
2014-12-21 10:41:03 +00:00
|
|
|
let negative = -&positive;
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
check(zero, unsigned_zero);
|
|
|
|
check(positive, BigUint::new(vec!(1,2,3)));
|
|
|
|
|
2015-01-09 21:54:32 +00:00
|
|
|
assert_eq!(negative.to_biguint(), None);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
2015-04-03 06:29:17 +00:00
|
|
|
const N1: BigDigit = -1i32 as BigDigit;
|
|
|
|
const N2: BigDigit = -2i32 as BigDigit;
|
|
|
|
|
2014-10-10 13:54:30 +00:00
|
|
|
const SUM_TRIPLES: &'static [(&'static [BigDigit],
|
|
|
|
&'static [BigDigit],
|
|
|
|
&'static [BigDigit])] = &[
|
2014-09-16 17:35:35 +00:00
|
|
|
(&[], &[], &[]),
|
|
|
|
(&[], &[ 1], &[ 1]),
|
|
|
|
(&[ 1], &[ 1], &[ 2]),
|
|
|
|
(&[ 1], &[ 1, 1], &[ 2, 1]),
|
2015-04-03 06:29:17 +00:00
|
|
|
(&[ 1], &[N1], &[ 0, 1]),
|
|
|
|
(&[ 1], &[N1, N1], &[ 0, 0, 1]),
|
|
|
|
(&[N1, N1], &[N1, N1], &[N2, N1, 1]),
|
|
|
|
(&[ 1, 1, 1], &[N1, N1], &[ 0, 1, 2]),
|
|
|
|
(&[ 2, 2, 1], &[N1, N2], &[ 1, 1, 2])
|
2014-09-16 17:35:35 +00:00
|
|
|
];
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_add() {
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in SUM_TRIPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec) = *elm;
|
|
|
|
let a = BigInt::from_slice(Plus, a_vec);
|
|
|
|
let b = BigInt::from_slice(Plus, b_vec);
|
|
|
|
let c = BigInt::from_slice(Plus, c_vec);
|
2015-11-16 19:06:39 +00:00
|
|
|
let (na, nb, nc) = (-&a, -&b, -&c);
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2015-11-16 19:06:39 +00:00
|
|
|
assert_op!(a + b == c);
|
|
|
|
assert_op!(b + a == c);
|
|
|
|
assert_op!(c + na == b);
|
|
|
|
assert_op!(c + nb == a);
|
|
|
|
assert_op!(a + nc == nb);
|
|
|
|
assert_op!(b + nc == na);
|
|
|
|
assert_op!(na + nb == nc);
|
|
|
|
assert_op!(a + na == Zero::zero());
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_sub() {
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in SUM_TRIPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec) = *elm;
|
|
|
|
let a = BigInt::from_slice(Plus, a_vec);
|
|
|
|
let b = BigInt::from_slice(Plus, b_vec);
|
|
|
|
let c = BigInt::from_slice(Plus, c_vec);
|
2015-11-16 19:06:39 +00:00
|
|
|
let (na, nb, nc) = (-&a, -&b, -&c);
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2015-11-16 19:06:39 +00:00
|
|
|
assert_op!(c - a == b);
|
|
|
|
assert_op!(c - b == a);
|
|
|
|
assert_op!(nb - a == nc);
|
|
|
|
assert_op!(na - b == nc);
|
|
|
|
assert_op!(b - na == c);
|
|
|
|
assert_op!(a - nb == c);
|
|
|
|
assert_op!(nc - na == nb);
|
|
|
|
assert_op!(a - a == Zero::zero());
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-04-02 16:37:32 +00:00
|
|
|
const M: u32 = ::std::u32::MAX;
|
2014-10-10 13:54:30 +00:00
|
|
|
static MUL_TRIPLES: &'static [(&'static [BigDigit],
|
2014-09-16 17:35:35 +00:00
|
|
|
&'static [BigDigit],
|
|
|
|
&'static [BigDigit])] = &[
|
|
|
|
(&[], &[], &[]),
|
|
|
|
(&[], &[ 1], &[]),
|
|
|
|
(&[ 2], &[], &[]),
|
|
|
|
(&[ 1], &[ 1], &[1]),
|
|
|
|
(&[ 2], &[ 3], &[ 6]),
|
|
|
|
(&[ 1], &[ 1, 1, 1], &[1, 1, 1]),
|
|
|
|
(&[ 1, 2, 3], &[ 3], &[ 3, 6, 9]),
|
2015-04-03 06:29:17 +00:00
|
|
|
(&[ 1, 1, 1], &[N1], &[N1, N1, N1]),
|
|
|
|
(&[ 1, 2, 3], &[N1], &[N1, N2, N2, 2]),
|
|
|
|
(&[ 1, 2, 3, 4], &[N1], &[N1, N2, N2, N2, 3]),
|
|
|
|
(&[N1], &[N1], &[ 1, N2]),
|
|
|
|
(&[N1, N1], &[N1], &[ 1, N1, N2]),
|
|
|
|
(&[N1, N1, N1], &[N1], &[ 1, N1, N1, N2]),
|
|
|
|
(&[N1, N1, N1, N1], &[N1], &[ 1, N1, N1, N1, N2]),
|
2015-04-02 16:37:32 +00:00
|
|
|
(&[ M/2 + 1], &[ 2], &[ 0, 1]),
|
|
|
|
(&[0, M/2 + 1], &[ 2], &[ 0, 0, 1]),
|
2014-09-16 17:35:35 +00:00
|
|
|
(&[ 1, 2], &[ 1, 2, 3], &[1, 4, 7, 6]),
|
2015-04-03 06:29:17 +00:00
|
|
|
(&[N1, N1], &[N1, N1, N1], &[1, 0, N1, N2, N1]),
|
|
|
|
(&[N1, N1, N1], &[N1, N1, N1, N1], &[1, 0, 0, N1, N2, N1, N1]),
|
2014-09-16 17:35:35 +00:00
|
|
|
(&[ 0, 0, 1], &[ 1, 2, 3], &[0, 0, 1, 2, 3]),
|
|
|
|
(&[ 0, 0, 1], &[ 0, 0, 0, 1], &[0, 0, 0, 0, 0, 1])
|
|
|
|
];
|
|
|
|
|
2014-10-10 13:54:30 +00:00
|
|
|
static DIV_REM_QUADRUPLES: &'static [(&'static [BigDigit],
|
2014-09-16 17:35:35 +00:00
|
|
|
&'static [BigDigit],
|
|
|
|
&'static [BigDigit],
|
|
|
|
&'static [BigDigit])]
|
|
|
|
= &[
|
|
|
|
(&[ 1], &[ 2], &[], &[1]),
|
2015-04-02 16:37:32 +00:00
|
|
|
(&[ 1, 1], &[ 2], &[ M/2+1], &[1]),
|
|
|
|
(&[ 1, 1, 1], &[ 2], &[ M/2+1, M/2+1], &[1]),
|
2015-04-03 06:29:17 +00:00
|
|
|
(&[ 0, 1], &[N1], &[1], &[1]),
|
|
|
|
(&[N1, N1], &[N2], &[2, 1], &[3])
|
2014-09-16 17:35:35 +00:00
|
|
|
];
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_mul() {
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in MUL_TRIPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec) = *elm;
|
|
|
|
let a = BigInt::from_slice(Plus, a_vec);
|
|
|
|
let b = BigInt::from_slice(Plus, b_vec);
|
|
|
|
let c = BigInt::from_slice(Plus, c_vec);
|
2015-11-16 19:06:39 +00:00
|
|
|
let (na, nb, nc) = (-&a, -&b, -&c);
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2015-11-16 19:06:39 +00:00
|
|
|
assert_op!(a * b == c);
|
|
|
|
assert_op!(b * a == c);
|
|
|
|
assert_op!(na * nb == c);
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2015-11-16 19:06:39 +00:00
|
|
|
assert_op!(na * b == nc);
|
|
|
|
assert_op!(nb * a == nc);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in DIV_REM_QUADRUPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec, d_vec) = *elm;
|
|
|
|
let a = BigInt::from_slice(Plus, a_vec);
|
|
|
|
let b = BigInt::from_slice(Plus, b_vec);
|
|
|
|
let c = BigInt::from_slice(Plus, c_vec);
|
|
|
|
let d = BigInt::from_slice(Plus, d_vec);
|
|
|
|
|
2014-12-16 14:38:35 +00:00
|
|
|
assert!(a == &b * &c + &d);
|
|
|
|
assert!(a == &c * &b + &d);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_div_mod_floor() {
|
|
|
|
fn check_sub(a: &BigInt, b: &BigInt, ans_d: &BigInt, ans_m: &BigInt) {
|
|
|
|
let (d, m) = a.div_mod_floor(b);
|
|
|
|
if !m.is_zero() {
|
|
|
|
assert_eq!(m.sign, b.sign);
|
|
|
|
}
|
|
|
|
assert!(m.abs() <= b.abs());
|
2014-12-16 14:38:35 +00:00
|
|
|
assert!(*a == b * &d + &m);
|
2014-09-16 17:35:35 +00:00
|
|
|
assert!(d == *ans_d);
|
|
|
|
assert!(m == *ans_m);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn check(a: &BigInt, b: &BigInt, d: &BigInt, m: &BigInt) {
|
|
|
|
if m.is_zero() {
|
|
|
|
check_sub(a, b, d, m);
|
|
|
|
check_sub(a, &b.neg(), &d.neg(), m);
|
|
|
|
check_sub(&a.neg(), b, &d.neg(), m);
|
|
|
|
check_sub(&a.neg(), &b.neg(), d, m);
|
|
|
|
} else {
|
2014-12-16 14:38:35 +00:00
|
|
|
let one: BigInt = One::one();
|
2014-09-16 17:35:35 +00:00
|
|
|
check_sub(a, b, d, m);
|
2014-12-16 14:38:35 +00:00
|
|
|
check_sub(a, &b.neg(), &(d.neg() - &one), &(m - b));
|
|
|
|
check_sub(&a.neg(), b, &(d.neg() - &one), &(b - m));
|
2014-09-16 17:35:35 +00:00
|
|
|
check_sub(&a.neg(), &b.neg(), d, &m.neg());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in MUL_TRIPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec) = *elm;
|
|
|
|
let a = BigInt::from_slice(Plus, a_vec);
|
|
|
|
let b = BigInt::from_slice(Plus, b_vec);
|
|
|
|
let c = BigInt::from_slice(Plus, c_vec);
|
|
|
|
|
|
|
|
if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); }
|
|
|
|
if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); }
|
|
|
|
}
|
|
|
|
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in DIV_REM_QUADRUPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec, d_vec) = *elm;
|
|
|
|
let a = BigInt::from_slice(Plus, a_vec);
|
|
|
|
let b = BigInt::from_slice(Plus, b_vec);
|
|
|
|
let c = BigInt::from_slice(Plus, c_vec);
|
|
|
|
let d = BigInt::from_slice(Plus, d_vec);
|
|
|
|
|
|
|
|
if !b.is_zero() {
|
|
|
|
check(&a, &b, &c, &d);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_div_rem() {
|
|
|
|
fn check_sub(a: &BigInt, b: &BigInt, ans_q: &BigInt, ans_r: &BigInt) {
|
|
|
|
let (q, r) = a.div_rem(b);
|
|
|
|
if !r.is_zero() {
|
|
|
|
assert_eq!(r.sign, a.sign);
|
|
|
|
}
|
|
|
|
assert!(r.abs() <= b.abs());
|
2014-12-16 14:38:35 +00:00
|
|
|
assert!(*a == b * &q + &r);
|
2014-09-16 17:35:35 +00:00
|
|
|
assert!(q == *ans_q);
|
|
|
|
assert!(r == *ans_r);
|
2015-11-16 19:06:39 +00:00
|
|
|
|
|
|
|
let (a, b, ans_q, ans_r) = (a.clone(), b.clone(), ans_q.clone(), ans_r.clone());
|
|
|
|
assert_op!(a / b == ans_q);
|
|
|
|
assert_op!(a % b == ans_r);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn check(a: &BigInt, b: &BigInt, q: &BigInt, r: &BigInt) {
|
|
|
|
check_sub(a, b, q, r);
|
|
|
|
check_sub(a, &b.neg(), &q.neg(), r);
|
|
|
|
check_sub(&a.neg(), b, &q.neg(), &r.neg());
|
|
|
|
check_sub(&a.neg(), &b.neg(), q, &r.neg());
|
|
|
|
}
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in MUL_TRIPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec) = *elm;
|
|
|
|
let a = BigInt::from_slice(Plus, a_vec);
|
|
|
|
let b = BigInt::from_slice(Plus, b_vec);
|
|
|
|
let c = BigInt::from_slice(Plus, c_vec);
|
|
|
|
|
|
|
|
if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); }
|
|
|
|
if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); }
|
|
|
|
}
|
|
|
|
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in DIV_REM_QUADRUPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec, d_vec) = *elm;
|
|
|
|
let a = BigInt::from_slice(Plus, a_vec);
|
|
|
|
let b = BigInt::from_slice(Plus, b_vec);
|
|
|
|
let c = BigInt::from_slice(Plus, c_vec);
|
|
|
|
let d = BigInt::from_slice(Plus, d_vec);
|
|
|
|
|
|
|
|
if !b.is_zero() {
|
|
|
|
check(&a, &b, &c, &d);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_checked_add() {
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in SUM_TRIPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec) = *elm;
|
|
|
|
let a = BigInt::from_slice(Plus, a_vec);
|
|
|
|
let b = BigInt::from_slice(Plus, b_vec);
|
|
|
|
let c = BigInt::from_slice(Plus, c_vec);
|
|
|
|
|
|
|
|
assert!(a.checked_add(&b).unwrap() == c);
|
|
|
|
assert!(b.checked_add(&a).unwrap() == c);
|
2014-12-21 10:41:03 +00:00
|
|
|
assert!(c.checked_add(&(-&a)).unwrap() == b);
|
|
|
|
assert!(c.checked_add(&(-&b)).unwrap() == a);
|
|
|
|
assert!(a.checked_add(&(-&c)).unwrap() == (-&b));
|
|
|
|
assert!(b.checked_add(&(-&c)).unwrap() == (-&a));
|
|
|
|
assert!((-&a).checked_add(&(-&b)).unwrap() == (-&c));
|
|
|
|
assert!(a.checked_add(&(-&a)).unwrap() == Zero::zero());
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_checked_sub() {
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in SUM_TRIPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec) = *elm;
|
|
|
|
let a = BigInt::from_slice(Plus, a_vec);
|
|
|
|
let b = BigInt::from_slice(Plus, b_vec);
|
|
|
|
let c = BigInt::from_slice(Plus, c_vec);
|
|
|
|
|
|
|
|
assert!(c.checked_sub(&a).unwrap() == b);
|
|
|
|
assert!(c.checked_sub(&b).unwrap() == a);
|
2014-12-21 10:41:03 +00:00
|
|
|
assert!((-&b).checked_sub(&a).unwrap() == (-&c));
|
|
|
|
assert!((-&a).checked_sub(&b).unwrap() == (-&c));
|
|
|
|
assert!(b.checked_sub(&(-&a)).unwrap() == c);
|
|
|
|
assert!(a.checked_sub(&(-&b)).unwrap() == c);
|
|
|
|
assert!((-&c).checked_sub(&(-&a)).unwrap() == (-&b));
|
2014-09-16 17:35:35 +00:00
|
|
|
assert!(a.checked_sub(&a).unwrap() == Zero::zero());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_checked_mul() {
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in MUL_TRIPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec) = *elm;
|
|
|
|
let a = BigInt::from_slice(Plus, a_vec);
|
|
|
|
let b = BigInt::from_slice(Plus, b_vec);
|
|
|
|
let c = BigInt::from_slice(Plus, c_vec);
|
|
|
|
|
|
|
|
assert!(a.checked_mul(&b).unwrap() == c);
|
|
|
|
assert!(b.checked_mul(&a).unwrap() == c);
|
|
|
|
|
2014-12-21 10:41:03 +00:00
|
|
|
assert!((-&a).checked_mul(&b).unwrap() == -&c);
|
|
|
|
assert!((-&b).checked_mul(&a).unwrap() == -&c);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in DIV_REM_QUADRUPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec, d_vec) = *elm;
|
|
|
|
let a = BigInt::from_slice(Plus, a_vec);
|
|
|
|
let b = BigInt::from_slice(Plus, b_vec);
|
|
|
|
let c = BigInt::from_slice(Plus, c_vec);
|
|
|
|
let d = BigInt::from_slice(Plus, d_vec);
|
|
|
|
|
2014-12-16 14:38:35 +00:00
|
|
|
assert!(a == b.checked_mul(&c).unwrap() + &d);
|
|
|
|
assert!(a == c.checked_mul(&b).unwrap() + &d);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
#[test]
|
|
|
|
fn test_checked_div() {
|
2014-10-10 13:54:30 +00:00
|
|
|
for elm in MUL_TRIPLES.iter() {
|
2014-09-16 17:35:35 +00:00
|
|
|
let (a_vec, b_vec, c_vec) = *elm;
|
|
|
|
let a = BigInt::from_slice(Plus, a_vec);
|
|
|
|
let b = BigInt::from_slice(Plus, b_vec);
|
|
|
|
let c = BigInt::from_slice(Plus, c_vec);
|
|
|
|
|
|
|
|
if !a.is_zero() {
|
|
|
|
assert!(c.checked_div(&a).unwrap() == b);
|
2014-12-21 10:41:03 +00:00
|
|
|
assert!((-&c).checked_div(&(-&a)).unwrap() == b);
|
|
|
|
assert!((-&c).checked_div(&a).unwrap() == -&b);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
if !b.is_zero() {
|
|
|
|
assert!(c.checked_div(&b).unwrap() == a);
|
2014-12-21 10:41:03 +00:00
|
|
|
assert!((-&c).checked_div(&(-&b)).unwrap() == a);
|
|
|
|
assert!((-&c).checked_div(&b).unwrap() == -&a);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
assert!(c.checked_div(&Zero::zero()).is_none());
|
2014-12-21 10:41:03 +00:00
|
|
|
assert!((-&c).checked_div(&Zero::zero()).is_none());
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_gcd() {
|
2015-01-09 11:36:03 +00:00
|
|
|
fn check(a: isize, b: isize, c: isize) {
|
2015-03-04 17:45:19 +00:00
|
|
|
let big_a: BigInt = FromPrimitive::from_isize(a).unwrap();
|
|
|
|
let big_b: BigInt = FromPrimitive::from_isize(b).unwrap();
|
|
|
|
let big_c: BigInt = FromPrimitive::from_isize(c).unwrap();
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
assert_eq!(big_a.gcd(&big_b), big_c);
|
|
|
|
}
|
|
|
|
|
|
|
|
check(10, 2, 2);
|
|
|
|
check(10, 3, 1);
|
|
|
|
check(0, 3, 3);
|
|
|
|
check(3, 3, 3);
|
|
|
|
check(56, 42, 14);
|
|
|
|
check(3, -3, 3);
|
|
|
|
check(-6, 3, 3);
|
|
|
|
check(-4, -2, 2);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_lcm() {
|
2015-01-09 11:36:03 +00:00
|
|
|
fn check(a: isize, b: isize, c: isize) {
|
2015-03-04 17:45:19 +00:00
|
|
|
let big_a: BigInt = FromPrimitive::from_isize(a).unwrap();
|
|
|
|
let big_b: BigInt = FromPrimitive::from_isize(b).unwrap();
|
|
|
|
let big_c: BigInt = FromPrimitive::from_isize(c).unwrap();
|
2014-09-16 17:35:35 +00:00
|
|
|
|
|
|
|
assert_eq!(big_a.lcm(&big_b), big_c);
|
|
|
|
}
|
|
|
|
|
|
|
|
check(1, 0, 0);
|
|
|
|
check(0, 1, 0);
|
|
|
|
check(1, 1, 1);
|
|
|
|
check(-1, 1, 1);
|
|
|
|
check(1, -1, 1);
|
|
|
|
check(-1, -1, 1);
|
|
|
|
check(8, 9, 72);
|
|
|
|
check(11, 5, 55);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_abs_sub() {
|
|
|
|
let zero: BigInt = Zero::zero();
|
|
|
|
let one: BigInt = One::one();
|
2014-12-21 10:41:03 +00:00
|
|
|
assert_eq!((-&one).abs_sub(&one), zero);
|
2014-09-16 17:35:35 +00:00
|
|
|
let one: BigInt = One::one();
|
|
|
|
let zero: BigInt = Zero::zero();
|
|
|
|
assert_eq!(one.abs_sub(&one), zero);
|
|
|
|
let one: BigInt = One::one();
|
|
|
|
let zero: BigInt = Zero::zero();
|
|
|
|
assert_eq!(one.abs_sub(&zero), one);
|
|
|
|
let one: BigInt = One::one();
|
2015-03-04 17:45:19 +00:00
|
|
|
let two: BigInt = FromPrimitive::from_isize(2).unwrap();
|
2014-12-21 10:41:03 +00:00
|
|
|
assert_eq!(one.abs_sub(&-&one), two);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_from_str_radix() {
|
2015-01-09 11:36:03 +00:00
|
|
|
fn check(s: &str, ans: Option<isize>) {
|
2014-09-16 17:35:35 +00:00
|
|
|
let ans = ans.map(|n| {
|
2015-03-04 17:45:19 +00:00
|
|
|
let x: BigInt = FromPrimitive::from_isize(n).unwrap();
|
2014-09-16 17:35:35 +00:00
|
|
|
x
|
|
|
|
});
|
2015-04-03 06:29:17 +00:00
|
|
|
assert_eq!(BigInt::from_str_radix(s, 10).ok(), ans);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
check("10", Some(10));
|
|
|
|
check("1", Some(1));
|
|
|
|
check("0", Some(0));
|
|
|
|
check("-1", Some(-1));
|
|
|
|
check("-10", Some(-10));
|
|
|
|
check("Z", None);
|
|
|
|
check("_", None);
|
|
|
|
|
|
|
|
// issue 10522, this hit an edge case that caused it to
|
|
|
|
// attempt to allocate a vector of size (-1u) == huge.
|
|
|
|
let x: BigInt =
|
2014-12-23 17:50:53 +00:00
|
|
|
format!("1{}", repeat("0").take(36).collect::<String>()).parse().unwrap();
|
2014-09-16 17:35:35 +00:00
|
|
|
let _y = x.to_string();
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_neg() {
|
|
|
|
assert!(-BigInt::new(Plus, vec!(1, 1, 1)) ==
|
|
|
|
BigInt::new(Minus, vec!(1, 1, 1)));
|
|
|
|
assert!(-BigInt::new(Minus, vec!(1, 1, 1)) ==
|
|
|
|
BigInt::new(Plus, vec!(1, 1, 1)));
|
|
|
|
let zero: BigInt = Zero::zero();
|
2014-12-21 10:41:03 +00:00
|
|
|
assert_eq!(-&zero, zero);
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_rand() {
|
2015-01-01 17:07:52 +00:00
|
|
|
let mut rng = thread_rng();
|
2014-09-16 17:35:35 +00:00
|
|
|
let _n: BigInt = rng.gen_bigint(137);
|
|
|
|
assert!(rng.gen_bigint(0).is_zero());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_rand_range() {
|
2015-01-01 17:07:52 +00:00
|
|
|
let mut rng = thread_rng();
|
2014-09-16 17:35:35 +00:00
|
|
|
|
2015-03-19 16:57:18 +00:00
|
|
|
for _ in 0..10 {
|
2015-03-04 17:45:19 +00:00
|
|
|
assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_usize(236).unwrap(),
|
|
|
|
&FromPrimitive::from_usize(237).unwrap()),
|
|
|
|
FromPrimitive::from_usize(236).unwrap());
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn check(l: BigInt, u: BigInt) {
|
2015-01-01 17:07:52 +00:00
|
|
|
let mut rng = thread_rng();
|
2015-03-19 16:57:18 +00:00
|
|
|
for _ in 0..1000 {
|
2014-09-16 17:35:35 +00:00
|
|
|
let n: BigInt = rng.gen_bigint_range(&l, &u);
|
|
|
|
assert!(n >= l);
|
|
|
|
assert!(n < u);
|
|
|
|
}
|
|
|
|
}
|
2015-03-04 17:45:19 +00:00
|
|
|
let l: BigInt = FromPrimitive::from_usize(403469000 + 2352).unwrap();
|
|
|
|
let u: BigInt = FromPrimitive::from_usize(403469000 + 3513).unwrap();
|
2014-09-16 17:35:35 +00:00
|
|
|
check( l.clone(), u.clone());
|
|
|
|
check(-l.clone(), u.clone());
|
|
|
|
check(-u.clone(), -l.clone());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2015-03-18 04:21:25 +00:00
|
|
|
#[should_panic]
|
2014-09-16 17:35:35 +00:00
|
|
|
fn test_zero_rand_range() {
|
2015-03-04 17:45:19 +00:00
|
|
|
thread_rng().gen_bigint_range(&FromPrimitive::from_isize(54).unwrap(),
|
|
|
|
&FromPrimitive::from_isize(54).unwrap());
|
2014-09-16 17:35:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2015-03-18 04:21:25 +00:00
|
|
|
#[should_panic]
|
2014-09-16 17:35:35 +00:00
|
|
|
fn test_negative_rand_range() {
|
2015-01-01 17:07:52 +00:00
|
|
|
let mut rng = thread_rng();
|
2015-03-04 17:45:19 +00:00
|
|
|
let l = FromPrimitive::from_usize(2352).unwrap();
|
|
|
|
let u = FromPrimitive::from_usize(3513).unwrap();
|
2014-09-16 17:35:35 +00:00
|
|
|
// Switching u and l should fail:
|
|
|
|
let _n: BigInt = rng.gen_bigint_range(&u, &l);
|
|
|
|
}
|
|
|
|
}
|