chore: checkpoint before Python removal

This commit is contained in:
2026-03-26 22:33:59 +00:00
parent 683cec9307
commit e568ddf82a
29972 changed files with 11269302 additions and 2 deletions

View File

@@ -0,0 +1,46 @@
use crate::big_digit::{BigDigit, DoubleBigDigit, BITS};
// Add with carry:
#[inline]
pub fn adc(a: BigDigit, b: BigDigit, acc: &mut DoubleBigDigit) -> BigDigit {
*acc += a as DoubleBigDigit;
*acc += b as DoubleBigDigit;
let lo = *acc as BigDigit;
*acc >>= BITS;
lo
}
// Only for the Add impl:
#[inline]
pub fn __add2(a: &mut [BigDigit], b: &[BigDigit]) -> BigDigit {
debug_assert!(a.len() >= b.len());
let mut carry = 0;
let (a_lo, a_hi) = a.split_at_mut(b.len());
for (a, b) in a_lo.iter_mut().zip(b) {
*a = adc(*a, *b, &mut carry);
}
if carry != 0 {
for a in a_hi {
*a = adc(*a, 0, &mut carry);
if carry == 0 {
break;
}
}
}
carry as BigDigit
}
/// /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.
pub fn add2(a: &mut [BigDigit], b: &[BigDigit]) {
let carry = __add2(a, b);
debug_assert!(carry == 0);
}

View File

@@ -0,0 +1,20 @@
use core::mem;
/// Find last set bit
/// fls(0) == 0, fls(u32::MAX) == 32
pub fn fls<T: num_traits::PrimInt>(v: T) -> usize {
mem::size_of::<T>() * 8 - v.leading_zeros() as usize
}
pub fn ilog2<T: num_traits::PrimInt>(v: T) -> usize {
fls(v) - 1
}
/// Divide two integers, and ceil the result.
pub fn idiv_ceil<T: num_traits::PrimInt>(a: T, b: T) -> T {
if a % b != T::zero() {
a / b + T::one()
} else {
a / b
}
}

View File

@@ -0,0 +1,49 @@
use core::cmp::Ordering::{self, Equal, Greater, Less};
use crate::big_digit::BigDigit;
pub 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;
}
}
Equal
}
#[cfg(test)]
mod tests {
use crate::BigUint;
use num_traits::Num;
#[test]
fn test_eq() {
let a = BigUint::from_str_radix("265252859812191058636308480000000", 10).unwrap();
let b = BigUint::from_str_radix("26525285981219105863630848000000", 10).unwrap();
assert!(a != b);
assert_ne!(a, b);
let a = BigUint::from_str_radix("138995801145388806366366393471481216294", 10).unwrap();
let b = BigUint::from_str_radix("168653801169012228514850424976871974699", 10).unwrap();
assert!(a != b);
assert_ne!(a, b);
assert!(&a != &b);
assert_ne!(&a, &b);
}
}

View File

@@ -0,0 +1,139 @@
use core::cmp::Ordering;
use num_traits::{One, Zero};
use smallvec::SmallVec;
use crate::algorithms::{add2, cmp_slice, sub2};
use crate::big_digit::{self, BigDigit, DoubleBigDigit};
use crate::BigUint;
pub fn div_rem_digit(mut a: BigUint, b: BigDigit) -> (BigUint, BigDigit) {
let mut rem = 0;
for d in a.data.iter_mut().rev() {
let (q, r) = div_wide(rem, *d, b);
*d = q;
rem = r;
}
(a.normalized(), rem)
}
/// Divide a two digit numerator by a one digit divisor, returns quotient and remainder:
///
/// Note: the caller must ensure that both the quotient and remainder will fit into a single digit.
/// This is _not_ true for an arbitrary numerator/denominator.
///
/// (This function also matches what the x86 divide instruction does).
#[inline]
pub fn div_wide(hi: BigDigit, lo: BigDigit, divisor: BigDigit) -> (BigDigit, BigDigit) {
debug_assert!(hi < divisor);
let lhs = big_digit::to_doublebigdigit(hi, lo);
let rhs = divisor as DoubleBigDigit;
((lhs / rhs) as BigDigit, (lhs % rhs) as BigDigit)
}
pub fn div_rem(u: &BigUint, d: &BigUint) -> (BigUint, BigUint) {
if d.is_zero() {
panic!()
}
if u.is_zero() {
return (Zero::zero(), Zero::zero());
}
if d.data.len() == 1 {
if d.data[0] == 1 {
return (u.clone(), Zero::zero());
}
let (div, rem) = div_rem_digit(u.clone(), d.data[0]);
return (div, rem.into());
}
// Required or the q_len calculation below can underflow:
match u.cmp(d) {
Ordering::Less => return (Zero::zero(), u.clone()),
Ordering::Equal => return (One::one(), Zero::zero()),
Ordering::Greater => {} // Do nothing
}
// This algorithm is from Knuth, TAOCP vol 2 section 4.3, algorithm D:
//
// First, normalize the arguments so the highest bit in the highest digit of the divisor is
// set: the main loop uses the highest digit of the divisor for generating guesses, so we
// want it to be the largest number we can efficiently divide by.
//
let shift = d.data.last().unwrap().leading_zeros() as usize;
let mut a = u << shift;
let b = d << shift;
// The algorithm works by incrementally calculating "guesses", q0, for part of the
// remainder. Once we have any number q0 such that q0 * b <= a, we can set
//
// q += q0
// a -= q0 * b
//
// and then iterate until a < b. Then, (q, a) will be our desired quotient and remainder.
//
// q0, our guess, is calculated by dividing the last few digits of a by the last digit of b
// - this should give us a guess that is "close" to the actual quotient, but is possibly
// greater than the actual quotient. If q0 * b > a, we simply use iterated subtraction
// until we have a guess such that q0 * b <= a.
//
let bn = *b.data.last().unwrap();
let q_len = a.data.len() - b.data.len() + 1;
let mut q = BigUint {
data: smallvec![0; q_len],
};
// We reuse the same temporary to avoid hitting the allocator in our inner loop - this is
// sized to hold a0 (in the common case; if a particular digit of the quotient is zero a0
// can be bigger).
//
let mut tmp = BigUint {
data: SmallVec::with_capacity(2),
};
for j in (0..q_len).rev() {
/*
* When calculating our next guess q0, we don't need to consider the digits below j
* + b.data.len() - 1: we're guessing digit j of the quotient (i.e. q0 << j) from
* digit bn of the divisor (i.e. bn << (b.data.len() - 1) - so the product of those
* two numbers will be zero in all digits up to (j + b.data.len() - 1).
*/
let offset = j + b.data.len() - 1;
if offset >= a.data.len() {
continue;
}
/* just avoiding a heap allocation: */
let mut a0 = tmp;
a0.data.truncate(0);
a0.data.extend(a.data[offset..].iter().cloned());
/*
* q0 << j * big_digit::BITS is our actual quotient estimate - we do the shifts
* implicitly at the end, when adding and subtracting to a and q. Not only do we
* save the cost of the shifts, the rest of the arithmetic gets to work with
* smaller numbers.
*/
let (mut q0, _) = div_rem_digit(a0, bn);
let mut prod = &b * &q0;
while cmp_slice(&prod.data[..], &a.data[j..]) == Ordering::Greater {
let one: BigUint = One::one();
q0 = q0 - one;
prod = prod - &b;
}
add2(&mut q.data[j..], &q0.data[..]);
sub2(&mut a.data[j..], &prod.data[..]);
a.normalize();
tmp = q0;
}
debug_assert!(a < b);
(q.normalized(), a >> shift)
}

View File

@@ -0,0 +1,751 @@
use crate::big_digit::{BigDigit, DoubleBigDigit, BITS};
use crate::bigint::Sign::*;
use crate::bigint::{BigInt, ToBigInt};
use crate::biguint::{BigUint, IntDigits};
use crate::integer::Integer;
use alloc::borrow::Cow;
use core::ops::Neg;
use num_traits::{One, Signed, Zero};
/// XGCD sets z to the greatest common divisor of a and b and returns z.
/// If extended is true, XGCD returns their value such that z = a*x + b*y.
///
/// Allow the inputs a and b to be zero or negative to GCD
/// with the following definitions.
///
/// If x or y are not nil, GCD sets their value such that z = a*x + b*y.
/// Regardless of the signs of a and b, z is always >= 0.
/// If a == b == 0, GCD sets z = x = y = 0.
/// If a == 0 and b != 0, GCD sets z = |b|, x = 0, y = sign(b) * 1.
/// If a != 0 and b == 0, GCD sets z = |a|, x = sign(a) * 1, y = 0.
pub fn xgcd(
a_in: &BigInt,
b_in: &BigInt,
extended: bool,
) -> (BigInt, Option<BigInt>, Option<BigInt>) {
//If a == b == 0, GCD sets z = x = y = 0.
if a_in.is_zero() && b_in.is_zero() {
if extended {
return (0.into(), Some(0.into()), Some(0.into()));
} else {
return (0.into(), None, None);
}
}
//If a == 0 and b != 0, GCD sets z = |b|, x = 0, y = sign(b) * 1.
// if a_in.is_zero() && !b_in.is_zero() {
if a_in.is_zero() {
if extended {
let mut y = BigInt::one();
if b_in.sign == Minus {
y.sign = Minus;
}
return (b_in.abs(), Some(0.into()), Some(y));
} else {
return (b_in.abs(), None, None);
}
}
//If a != 0 and b == 0, GCD sets z = |a|, x = sign(a) * 1, y = 0.
//if !a_in.is_zero() && b_in.is_zero() {
if b_in.is_zero() {
if extended {
let mut x = BigInt::one();
if a_in.sign == Minus {
x.sign = Minus;
}
return (a_in.abs(), Some(x), Some(0.into()));
} else {
return (a_in.abs(), None, None);
}
}
lehmer_gcd(a_in, b_in, extended)
}
/// lehmerGCD sets z to the greatest common divisor of a and b,
/// which both must be != 0, and returns z.
/// If x or y are not nil, their values are set such that z = a*x + b*y.
/// See Knuth, The Art of Computer Programming, Vol. 2, Section 4.5.2, Algorithm L.
/// This implementation uses the improved condition by Collins requiring only one
/// quotient and avoiding the possibility of single Word overflow.
/// See Jebelean, "Improving the multiprecision Euclidean algorithm",
/// Design and Implementation of Symbolic Computation Systems, pp 45-58.
/// The cosequences are updated according to Algorithm 10.45 from
/// Cohen et al. "Handbook of Elliptic and Hyperelliptic Curve Cryptography" pp 192.
fn lehmer_gcd(
a_in: &BigInt,
b_in: &BigInt,
extended: bool,
) -> (BigInt, Option<BigInt>, Option<BigInt>) {
let mut a = a_in.clone();
let mut b = b_in.clone();
//essential absolute value on both a & b
a.sign = Plus;
b.sign = Plus;
// `ua` (`ub`) tracks how many times input `a_in` has beeen accumulated into `a` (`b`).
let mut ua = if extended { Some(1.into()) } else { None };
let mut ub = if extended { Some(0.into()) } else { None };
// temp variables for multiprecision update
let mut q: BigInt = 0.into();
let mut r: BigInt = 0.into();
let mut s: BigInt = 0.into();
let mut t: BigInt = 0.into();
// Ensure that a >= b
if a < b {
core::mem::swap(&mut a, &mut b);
core::mem::swap(&mut ua, &mut ub);
}
// loop invariant A >= B
while b.len() > 1 {
// Attempt to calculate in single-precision using leading words of a and b.
let (u0, u1, v0, v1, even) = lehmer_simulate(&a, &b);
// multiprecision step
if v0 != 0 {
// Simulate the effect of the single-precision steps using cosequences.
// a = u0 * a + v0 * b
// b = u1 * a + v1 * b
lehmer_update(
&mut a, &mut b, &mut q, &mut r, &mut s, &mut t, u0, u1, v0, v1, even,
);
if extended {
// ua = u0 * ua + v0 * ub
// ub = u1 * ua + v1 * ub
lehmer_update(
ua.as_mut().unwrap(),
ub.as_mut().unwrap(),
&mut q,
&mut r,
&mut s,
&mut t,
u0,
u1,
v0,
v1,
even,
);
}
} else {
// Single-digit calculations failed to simulate any quotients.
euclid_udpate(
&mut a, &mut b, &mut ua, &mut ub, &mut q, &mut r, &mut s, &mut t, extended,
);
}
}
if b.len() > 0 {
// base case if b is a single digit
if a.len() > 1 {
// a is longer than a single word, so one update is needed
euclid_udpate(
&mut a, &mut b, &mut ua, &mut ub, &mut q, &mut r, &mut s, &mut t, extended,
);
}
if b.len() > 0 {
// a and b are both single word
let mut a_word = a.digits()[0];
let mut b_word = b.digits()[0];
if extended {
let mut ua_word: BigDigit = 1;
let mut ub_word: BigDigit = 0;
let mut va: BigDigit = 0;
let mut vb: BigDigit = 1;
let mut even = true;
while b_word != 0 {
let q = a_word / b_word;
let r = a_word % b_word;
a_word = b_word;
b_word = r;
let k = ua_word.wrapping_add(q.wrapping_mul(ub_word));
ua_word = ub_word;
ub_word = k;
let k = va.wrapping_add(q.wrapping_mul(vb));
va = vb;
vb = k;
even = !even;
}
t.data.set_digit(ua_word);
s.data.set_digit(va);
t.sign = if even { Plus } else { Minus };
s.sign = if even { Minus } else { Plus };
if let Some(ua) = ua.as_mut() {
t *= &*ua;
s *= ub.unwrap();
*ua = &t + &s;
}
} else {
while b_word != 0 {
let quotient = a_word % b_word;
a_word = b_word;
b_word = quotient;
}
}
a.digits_mut()[0] = a_word;
}
}
a.normalize();
//Sign fixing
let mut neg_a: bool = false;
if a_in.sign == Minus {
neg_a = true;
}
let y = if let Some(ref mut ua) = ua {
// y = (z - a * x) / b
//a_in*x
let mut tmp = a_in * &*ua;
if neg_a {
tmp.sign = tmp.sign.neg();
ua.sign = ua.sign.neg();
}
//z - (a_in * x)
tmp = &a - &tmp;
tmp = &tmp / b_in;
Some(tmp)
} else {
None
};
a.sign = Plus;
(a, ua, y)
}
/// Uses the lehemer algorithm.
/// Based on https://github.com/golang/go/blob/master/src/math/big/int.go#L612
/// If `extended` is set, the Bezout coefficients are calculated, otherwise they are `None`.
pub fn extended_gcd(
a_in: Cow<BigUint>,
b_in: Cow<BigUint>,
extended: bool,
) -> (BigInt, Option<BigInt>, Option<BigInt>) {
if a_in.is_zero() && b_in.is_zero() {
if extended {
return (b_in.to_bigint().unwrap(), Some(0.into()), Some(0.into()));
} else {
return (b_in.to_bigint().unwrap(), None, None);
}
}
if a_in.is_zero() {
if extended {
return (b_in.to_bigint().unwrap(), Some(0.into()), Some(1.into()));
} else {
return (b_in.to_bigint().unwrap(), None, None);
}
}
if b_in.is_zero() {
if extended {
return (a_in.to_bigint().unwrap(), Some(1.into()), Some(0.into()));
} else {
return (a_in.to_bigint().unwrap(), None, None);
}
}
let a_in = a_in.to_bigint().unwrap();
let b_in = b_in.to_bigint().unwrap();
let mut a = a_in.clone();
let mut b = b_in.clone();
// `ua` (`ub`) tracks how many times input `a_in` has beeen accumulated into `a` (`b`).
let mut ua = if extended { Some(1.into()) } else { None };
let mut ub = if extended { Some(0.into()) } else { None };
// Ensure that a >= b
if a < b {
core::mem::swap(&mut a, &mut b);
core::mem::swap(&mut ua, &mut ub);
}
let mut q: BigInt = 0.into();
let mut r: BigInt = 0.into();
let mut s: BigInt = 0.into();
let mut t: BigInt = 0.into();
while b.len() > 1 {
// Attempt to calculate in single-precision using leading words of a and b.
let (u0, u1, v0, v1, even) = lehmer_simulate(&a, &b);
// multiprecision step
if v0 != 0 {
// Simulate the effect of the single-precision steps using cosequences.
// a = u0 * a + v0 * b
// b = u1 * a + v1 * b
lehmer_update(
&mut a, &mut b, &mut q, &mut r, &mut s, &mut t, u0, u1, v0, v1, even,
);
if extended {
// ua = u0 * ua + v0 * ub
// ub = u1 * ua + v1 * ub
lehmer_update(
ua.as_mut().unwrap(),
ub.as_mut().unwrap(),
&mut q,
&mut r,
&mut s,
&mut t,
u0,
u1,
v0,
v1,
even,
);
}
} else {
// Single-digit calculations failed to simulate any quotients.
euclid_udpate(
&mut a, &mut b, &mut ua, &mut ub, &mut q, &mut r, &mut s, &mut t, extended,
);
}
}
if b.len() > 0 {
// base case if b is a single digit
if a.len() > 1 {
// a is longer than a single word, so one update is needed
euclid_udpate(
&mut a, &mut b, &mut ua, &mut ub, &mut q, &mut r, &mut s, &mut t, extended,
);
}
if b.len() > 0 {
// a and b are both single word
let mut a_word = a.digits()[0];
let mut b_word = b.digits()[0];
if extended {
let mut ua_word: BigDigit = 1;
let mut ub_word: BigDigit = 0;
let mut va: BigDigit = 0;
let mut vb: BigDigit = 1;
let mut even = true;
while b_word != 0 {
let q = a_word / b_word;
let r = a_word % b_word;
a_word = b_word;
b_word = r;
let k = ua_word.wrapping_add(q.wrapping_mul(ub_word));
ua_word = ub_word;
ub_word = k;
let k = va.wrapping_add(q.wrapping_mul(vb));
va = vb;
vb = k;
even = !even;
}
t.data.set_digit(ua_word);
s.data.set_digit(va);
t.sign = if even { Plus } else { Minus };
s.sign = if even { Minus } else { Plus };
if let Some(ua) = ua.as_mut() {
t *= &*ua;
s *= ub.unwrap();
*ua = &t + &s;
}
} else {
while b_word != 0 {
let quotient = a_word % b_word;
a_word = b_word;
b_word = quotient;
}
}
a.digits_mut()[0] = a_word;
}
}
a.normalize();
let y = if let Some(ref ua) = ua {
// y = (z - a * x) / b
Some((&a - (&a_in * ua)) / &b_in)
} else {
None
};
(a, ua, y)
}
/// Attempts to simulate several Euclidean update steps using leading digits of `a` and `b`.
/// It returns `u0`, `u1`, `v0`, `v1` such that `a` and `b` can be updated as:
/// a = u0 * a + v0 * b
/// b = u1 * a + v1 * b
///
/// Requirements: `a >= b` and `b.len() > 2`.
/// Since we are calculating with full words to avoid overflow, `even` (the returned bool)
/// is used to track the sign of cosequences.
/// For even iterations: `u0, v1 >= 0 && u1, v0 <= 0`
/// For odd iterations: `u0, v1 <= && u1, v0 >= 0`
#[inline]
fn lehmer_simulate(a: &BigInt, b: &BigInt) -> (BigDigit, BigDigit, BigDigit, BigDigit, bool) {
// m >= 2
let m = b.len();
// n >= m >= 2
let n = a.len();
// println!("a len is {:?}", a.len());
// println!("b len is {:?}", b.len());
// debug_assert!(m >= 2);
// debug_assert!(n >= m);
// extract the top word of bits from a and b
let h = a.digits()[n - 1].leading_zeros();
let mut a1: BigDigit = a.digits()[n - 1] << h
| ((a.digits()[n - 2] as DoubleBigDigit) >> (BITS as u32 - h)) as BigDigit;
// b may have implicit zero words in the high bits if the lengths differ
let mut a2: BigDigit = if n == m {
b.digits()[n - 1] << h
| ((b.digits()[n - 2] as DoubleBigDigit) >> (BITS as u32 - h)) as BigDigit
} else if n == m + 1 {
((b.digits()[n - 2] as DoubleBigDigit) >> (BITS as u32 - h)) as BigDigit
} else {
0
};
// odd, even tracking
let mut even = false;
let mut u0 = 0;
let mut u1 = 1;
let mut u2 = 0;
let mut v0 = 0;
let mut v1 = 0;
let mut v2 = 1;
// Calculate the quotient and cosequences using Collins' stoppting condition.
while a2 >= v2 && a1.wrapping_sub(a2) >= v1 + v2 {
let q = a1 / a2;
let r = a1 % a2;
a1 = a2;
a2 = r;
let k = u1 + q * u2;
u0 = u1;
u1 = u2;
u2 = k;
let k = v1 + q * v2;
v0 = v1;
v1 = v2;
v2 = k;
even = !even;
}
(u0, u1, v0, v1, even)
}
fn lehmer_update(
a: &mut BigInt,
b: &mut BigInt,
q: &mut BigInt,
r: &mut BigInt,
s: &mut BigInt,
t: &mut BigInt,
u0: BigDigit,
u1: BigDigit,
v0: BigDigit,
v1: BigDigit,
even: bool,
) {
t.data.set_digit(u0);
s.data.set_digit(v0);
if even {
t.sign = Plus;
s.sign = Minus
} else {
t.sign = Minus;
s.sign = Plus;
}
*t *= &*a;
*s *= &*b;
r.data.set_digit(u1);
q.data.set_digit(v1);
if even {
q.sign = Plus;
r.sign = Minus
} else {
q.sign = Minus;
r.sign = Plus;
}
*r *= &*a;
*q *= &*b;
*a = t + s;
*b = r + q;
}
fn euclid_udpate(
a: &mut BigInt,
b: &mut BigInt,
ua: &mut Option<BigInt>,
ub: &mut Option<BigInt>,
q: &mut BigInt,
r: &mut BigInt,
s: &mut BigInt,
t: &mut BigInt,
extended: bool,
) {
let (q_new, r_new) = a.div_rem(b);
*q = q_new;
*r = r_new;
core::mem::swap(a, b);
core::mem::swap(b, r);
if extended {
// ua, ub = ub, ua - q * ub
if let Some(ub) = ub.as_mut() {
if let Some(ua) = ua.as_mut() {
*t = ub.clone();
*s = &*ub * &*q;
*ub = &*ua - &*s;
*ua = t.clone();
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use core::str::FromStr;
use num_traits::FromPrimitive;
#[cfg(feature = "rand")]
use crate::bigrand::RandBigInt;
#[cfg(feature = "rand")]
use num_traits::{One, Zero};
#[cfg(feature = "rand")]
use rand::SeedableRng;
#[cfg(feature = "rand")]
use rand_xorshift::XorShiftRng;
#[cfg(feature = "rand")]
fn extended_gcd_euclid(a: Cow<BigUint>, b: Cow<BigUint>) -> (BigInt, BigInt, BigInt) {
// use crate::bigint::ToBigInt;
if a.is_zero() && b.is_zero() {
return (0.into(), 0.into(), 0.into());
}
let (mut s, mut old_s) = (BigInt::zero(), BigInt::one());
let (mut t, mut old_t) = (BigInt::one(), BigInt::zero());
let (mut r, mut old_r) = (b.to_bigint().unwrap(), a.to_bigint().unwrap());
while !r.is_zero() {
let quotient = &old_r / &r;
old_r = old_r - &quotient * &r;
core::mem::swap(&mut old_r, &mut r);
old_s = old_s - &quotient * &s;
core::mem::swap(&mut old_s, &mut s);
old_t = old_t - quotient * &t;
core::mem::swap(&mut old_t, &mut t);
}
(old_r, old_s, old_t)
}
#[test]
#[cfg(feature = "rand")]
fn test_extended_gcd_assumptions() {
let mut rng = XorShiftRng::from_seed([1u8; 16]);
for i in 1usize..100 {
for j in &[1usize, 64, 128] {
//println!("round {} - {}", i, j);
let a = rng.gen_biguint(i * j);
let b = rng.gen_biguint(i * j);
let (q, s_k, t_k) = extended_gcd(Cow::Borrowed(&a), Cow::Borrowed(&b), true);
let lhs = BigInt::from_biguint(Plus, a) * &s_k.unwrap();
let rhs = BigInt::from_biguint(Plus, b) * &t_k.unwrap();
assert_eq!(q.clone(), &lhs + &rhs, "{} = {} + {}", q, lhs, rhs);
}
}
}
#[test]
fn test_extended_gcd_example() {
// simple example for wikipedia
let a = BigUint::from_u32(240).unwrap();
let b = BigUint::from_u32(46).unwrap();
let (q, s_k, t_k) = extended_gcd(Cow::Owned(a), Cow::Owned(b), true);
assert_eq!(q, BigInt::from_i32(2).unwrap());
assert_eq!(s_k.unwrap(), BigInt::from_i32(-9).unwrap());
assert_eq!(t_k.unwrap(), BigInt::from_i32(47).unwrap());
}
#[test]
fn test_extended_gcd_example_not_extended() {
// simple example for wikipedia
let a = BigUint::from_u32(240).unwrap();
let b = BigUint::from_u32(46).unwrap();
let (q, s_k, t_k) = extended_gcd(Cow::Owned(a), Cow::Owned(b), false);
assert_eq!(q, BigInt::from_i32(2).unwrap());
assert_eq!(s_k, None);
assert_eq!(t_k, None);
}
#[test]
fn test_extended_gcd_example_wolfram() {
// https://www.wolframalpha.com/input/?i=ExtendedGCD%5B-565721958+,+4486780496%5D
// https://github.com/Chia-Network/oldvdf-competition/blob/master/tests/test_classgroup.py#L109
let a = BigInt::from_str("-565721958").unwrap();
let b = BigInt::from_str("4486780496").unwrap();
let (q, _s_k, _t_k) = xgcd(&a, &b, true);
assert_eq!(q, BigInt::from(2));
assert_eq!(_s_k, Some(BigInt::from(-1090996795)));
assert_eq!(_t_k, Some(BigInt::from(-137559848)));
}
#[test]
fn test_golang_bignum_negative() {
// a <= 0 || b <= 0
//d, x, y, a, b string
let gcd_test_cases = [
["0", "0", "0", "0", "0"],
["7", "0", "1", "0", "7"],
["7", "0", "-1", "0", "-7"],
["11", "1", "0", "11", "0"],
["7", "-1", "-2", "-77", "35"],
["935", "-3", "8", "64515", "24310"],
["935", "-3", "-8", "64515", "-24310"],
["935", "3", "-8", "-64515", "-24310"],
["1", "-9", "47", "120", "23"],
["7", "1", "-2", "77", "35"],
["935", "-3", "8", "64515", "24310"],
[
"935000000000000000",
"-3",
"8",
"64515000000000000000",
"24310000000000000000",
],
[
"1",
"-221",
"22059940471369027483332068679400581064239780177629666810348940098015901108344",
"98920366548084643601728869055592650835572950932266967461790948584315647051443",
"991",
],
];
for t in 0..gcd_test_cases.len() {
//d, x, y, a, b string
let d_case = BigInt::from_str(gcd_test_cases[t][0]).unwrap();
let x_case = BigInt::from_str(gcd_test_cases[t][1]).unwrap();
let y_case = BigInt::from_str(gcd_test_cases[t][2]).unwrap();
let a_case = BigInt::from_str(gcd_test_cases[t][3]).unwrap();
let b_case = BigInt::from_str(gcd_test_cases[t][4]).unwrap();
// println!("round is {:?}", t);
// println!("a len is {:?}", a_case.len());
// println!("b len is {:?}", b_case.len());
// println!("a is {:?}", &a_case);
// println!("b is {:?}", &b_case);
//testGcd(d, nil, nil, a, b)
//testGcd(d, x, y, a, b)
let (_d, _x, _y) = xgcd(&a_case, &b_case, false);
assert_eq!(_d, d_case);
assert_eq!(_x, None);
assert_eq!(_y, None);
let (_d, _x, _y) = xgcd(&a_case, &b_case, true);
assert_eq!(_d, d_case);
assert_eq!(_x.unwrap(), x_case);
assert_eq!(_y.unwrap(), y_case);
}
}
#[test]
#[cfg(feature = "rand")]
fn test_gcd_lehmer_euclid_extended() {
let mut rng = XorShiftRng::from_seed([1u8; 16]);
for i in 1usize..80 {
for j in &[1usize, 16, 24, 64, 128] {
//println!("round {} - {}", i, j);
let a = rng.gen_biguint(i * j);
let b = rng.gen_biguint(i * j);
let (q, s_k, t_k) = extended_gcd(Cow::Borrowed(&a), Cow::Borrowed(&b), true);
let expected = extended_gcd_euclid(Cow::Borrowed(&a), Cow::Borrowed(&b));
assert_eq!(q, expected.0);
assert_eq!(s_k.unwrap(), expected.1);
assert_eq!(t_k.unwrap(), expected.2);
}
}
}
#[test]
#[cfg(feature = "rand")]
fn test_gcd_lehmer_euclid_not_extended() {
let mut rng = XorShiftRng::from_seed([1u8; 16]);
for i in 1usize..80 {
for j in &[1usize, 16, 24, 64, 128] {
//println!("round {} - {}", i, j);
let a = rng.gen_biguint(i * j);
let b = rng.gen_biguint(i * j);
let (q, s_k, t_k) = extended_gcd(Cow::Borrowed(&a), Cow::Borrowed(&b), false);
let expected = extended_gcd_euclid(Cow::Borrowed(&a), Cow::Borrowed(&b));
assert_eq!(
q, expected.0,
"gcd({}, {}) = {} != {}",
&a, &b, &q, expected.0
);
assert_eq!(s_k, None);
assert_eq!(t_k, None);
}
}
}
}

View File

@@ -0,0 +1,100 @@
use crate::integer::Integer;
use num_traits::{One, Signed, Zero};
use crate::BigInt;
/// Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0.
/// The y argument must be an odd integer.
pub fn jacobi(x: &BigInt, y: &BigInt) -> isize {
if !y.is_odd() {
panic!(
"invalid arguments, y must be an odd integer,but got {:?}",
y
);
}
let mut a = x.clone();
let mut b = y.clone();
let mut j = 1;
if b.is_negative() {
if a.is_negative() {
j = -1;
}
b = -b;
}
loop {
if b.is_one() {
return j;
}
if a.is_zero() {
return 0;
}
a = a.mod_floor(&b);
if a.is_zero() {
return 0;
}
// a > 0
// handle factors of 2 in a
let s = a.trailing_zeros().unwrap();
if s & 1 != 0 {
let bmod8 = b.get_limb(0) & 7;
if bmod8 == 3 || bmod8 == 5 {
j = -j;
}
}
let c = &a >> s; // a = 2^s*c
// swap numerator and denominator
if b.get_limb(0) & 3 == 3 && c.get_limb(0) & 3 == 3 {
j = -j
}
a = b;
b = c;
}
}
#[cfg(test)]
mod tests {
use super::*;
use num_traits::FromPrimitive;
use crate::BigInt;
#[test]
fn test_jacobi() {
let cases = [
[0, 1, 1],
[0, -1, 1],
[1, 1, 1],
[1, -1, 1],
[0, 5, 0],
[1, 5, 1],
[2, 5, -1],
[-2, 5, -1],
[2, -5, -1],
[-2, -5, 1],
[3, 5, -1],
[5, 5, 0],
[-5, 5, 0],
[6, 5, 1],
[6, -5, 1],
[-6, 5, 1],
[-6, -5, -1],
];
for case in cases.iter() {
let x = BigInt::from_i64(case[0]).unwrap();
let y = BigInt::from_i64(case[1]).unwrap();
assert_eq!(case[2] as isize, jacobi(&x, &y), "jacobi({}, {})", x, y);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,27 @@
#![allow(clippy::many_single_char_names)]
mod add;
mod bits;
mod cmp;
mod div;
mod gcd;
mod jacobi;
mod mac;
mod mod_inverse;
mod mul;
mod shl;
mod shr;
mod sub;
pub use self::add::*;
pub use self::bits::*;
pub use self::cmp::*;
pub use self::div::*;
pub use self::gcd::*;
pub use self::jacobi::*;
pub use self::mac::*;
pub use self::mod_inverse::*;
pub use self::mul::*;
pub use self::shl::*;
pub use self::shr::*;
pub use self::sub::*;

View File

@@ -0,0 +1,100 @@
use alloc::borrow::Cow;
use num_traits::{One, Signed};
use crate::algorithms::extended_gcd;
use crate::{BigInt, BigUint};
/// Calculate the modular inverse of `g`.
/// Implementation is based on the naive version from wikipedia.
#[inline]
pub fn mod_inverse(g: Cow<BigUint>, n: Cow<BigUint>) -> Option<BigInt> {
let (d, x, _) = extended_gcd(g, n.clone(), true);
if !d.is_one() {
return None;
}
let x = x.unwrap();
if x.is_negative() {
Some(x + n.as_ref())
} else {
Some(x)
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
use num_traits::FromPrimitive;
use crate::integer::Integer;
use crate::traits::ModInverse;
#[test]
fn test_mod_inverse() {
let tests = [
["1234567", "458948883992"],
[
"239487239847",
"2410312426921032588552076022197566074856950548502459942654116941958108831682612228890093858261341614673227141477904012196503648957050582631942730706805009223062734745341073406696246014589361659774041027169249453200378729434170325843778659198143763193776859869524088940195577346119843545301547043747207749969763750084308926339295559968882457872412993810129130294592999947926365264059284647209730384947211681434464714438488520940127459844288859336526896320919633919",
],
["-10", "13"],
["-6193420858199668535", "2881"],
];
for test in &tests {
let element = BigInt::parse_bytes(test[0].as_bytes(), 10).unwrap();
let modulus = BigInt::parse_bytes(test[1].as_bytes(), 10).unwrap();
//println!("{} modinv {}", element, modulus);
let inverse = element.clone().mod_inverse(&modulus).unwrap();
//println!("inverse: {}", &inverse);
let cmp = (inverse * &element).mod_floor(&modulus);
assert_eq!(
cmp,
BigInt::one(),
"mod_inverse({}, {}) * {} % {} = {}, not 1",
&element,
&modulus,
&element,
&modulus,
&cmp
);
}
// exhaustive tests for small numbers
for n in 2..100 {
let modulus = BigInt::from_u64(n).unwrap();
for x in 1..n {
for sign in vec![1i64, -1i64] {
let element = BigInt::from_i64(sign * x as i64).unwrap();
let gcd = element.gcd(&modulus);
if !gcd.is_one() {
continue;
}
let inverse = element.clone().mod_inverse(&modulus).unwrap();
let cmp = (&inverse * &element).mod_floor(&modulus);
//println!("inverse: {}", &inverse);
assert_eq!(
cmp,
BigInt::one(),
"mod_inverse({}, {}) * {} % {} = {}, not 1",
&element,
&modulus,
&element,
&modulus,
&cmp
);
}
}
}
}
}

View File

@@ -0,0 +1,29 @@
use crate::algorithms::mac3;
use crate::big_digit::{BigDigit, DoubleBigDigit, BITS};
use crate::BigUint;
#[inline]
pub fn mul_with_carry(a: BigDigit, b: BigDigit, acc: &mut DoubleBigDigit) -> BigDigit {
*acc += (a as DoubleBigDigit) * (b as DoubleBigDigit);
let lo = *acc as BigDigit;
*acc >>= BITS;
lo
}
pub fn mul3(x: &[BigDigit], y: &[BigDigit]) -> BigUint {
let len = x.len() + y.len() + 1;
let mut prod = BigUint {
data: smallvec![0; len],
};
mac3(&mut prod.data[..], x, y);
prod.normalized()
}
pub fn scalar_mul(a: &mut [BigDigit], b: BigDigit) -> BigDigit {
let mut carry = 0;
for a in a.iter_mut() {
*a = mul_with_carry(*a, b, &mut carry);
}
carry as BigDigit
}

View File

@@ -0,0 +1,37 @@
use alloc::borrow::Cow;
use core::iter::repeat;
use smallvec::SmallVec;
use crate::big_digit::BITS;
use crate::BigUint;
#[inline]
pub fn biguint_shl(n: Cow<BigUint>, bits: usize) -> BigUint {
let n_unit = bits / BITS;
let mut data = match n_unit {
0 => n.into_owned().data,
_ => {
let len = n_unit + n.data.len() + 1;
let mut data = SmallVec::with_capacity(len);
data.extend(repeat(0).take(n_unit));
data.extend(n.data.iter().cloned());
data
}
};
let n_bits = bits % BITS;
if n_bits > 0 {
let mut carry = 0;
for elem in data[n_unit..].iter_mut() {
let new_carry = *elem >> (BITS - n_bits);
*elem = (*elem << n_bits) | carry;
carry = new_carry;
}
if carry != 0 {
data.push(carry);
}
}
BigUint::new_native(data)
}

View File

@@ -0,0 +1,32 @@
use alloc::borrow::Cow;
use num_traits::Zero;
use smallvec::SmallVec;
use crate::big_digit::{BigDigit, BITS};
use crate::BigUint;
use crate::VEC_SIZE;
#[inline]
pub fn biguint_shr(n: Cow<BigUint>, bits: usize) -> BigUint {
let n_unit = bits / BITS;
if n_unit >= n.data.len() {
return Zero::zero();
}
let mut data: SmallVec<[BigDigit; VEC_SIZE]> = match n {
Cow::Borrowed(n) => n.data[n_unit..].into(),
Cow::Owned(n) => n.data[n_unit..].into(),
};
let n_bits = bits % BITS;
if n_bits > 0 {
let mut borrow = 0;
for elem in data.iter_mut().rev() {
let new_borrow = *elem << (BITS - n_bits);
*elem = (*elem >> n_bits) | borrow;
borrow = new_borrow;
}
}
BigUint::new_native(data)
}

View File

@@ -0,0 +1,124 @@
use core::cmp;
use core::cmp::Ordering::*;
use num_traits::Zero;
use smallvec::SmallVec;
use crate::algorithms::cmp_slice;
use crate::big_digit::{BigDigit, SignedDoubleBigDigit, BITS};
use crate::bigint::Sign::{self, *};
use crate::{BigUint, VEC_SIZE};
/// Subtract with borrow:
#[inline]
pub fn sbb(a: BigDigit, b: BigDigit, acc: &mut SignedDoubleBigDigit) -> BigDigit {
*acc += a as SignedDoubleBigDigit;
*acc -= b as SignedDoubleBigDigit;
let lo = *acc as BigDigit;
*acc >>= BITS;
lo
}
pub fn sub2(a: &mut [BigDigit], b: &[BigDigit]) {
let mut borrow = 0;
let len = cmp::min(a.len(), b.len());
let (a_lo, a_hi) = a.split_at_mut(len);
let (b_lo, b_hi) = b.split_at(len);
for (a, b) in a_lo.iter_mut().zip(b_lo) {
*a = sbb(*a, *b, &mut borrow);
}
if borrow != 0 {
for a in a_hi {
*a = sbb(*a, 0, &mut borrow);
if borrow == 0 {
break;
}
}
}
// note: we're _required_ to fail on underflow
assert!(
borrow == 0 && b_hi.iter().all(|x| *x == 0),
"Cannot subtract b from a because b is larger than a."
);
}
// Only for the Sub impl. `a` and `b` must have same length.
#[inline]
pub fn __sub2rev(a: &[BigDigit], b: &mut [BigDigit]) -> BigDigit {
debug_assert!(b.len() == a.len());
let mut borrow = 0;
for (ai, bi) in a.iter().zip(b) {
*bi = sbb(*ai, *bi, &mut borrow);
}
borrow as BigDigit
}
pub fn sub2rev(a: &[BigDigit], b: &mut [BigDigit]) {
debug_assert!(b.len() >= a.len());
let len = cmp::min(a.len(), b.len());
let (a_lo, a_hi) = a.split_at(len);
let (b_lo, b_hi) = b.split_at_mut(len);
let borrow = __sub2rev(a_lo, b_lo);
assert!(a_hi.is_empty());
// note: we're _required_ to fail on underflow
assert!(
borrow == 0 && b_hi.iter().all(|x| *x == 0),
"Cannot subtract b from a because b is larger than a."
);
}
pub fn sub_sign(a: &[BigDigit], b: &[BigDigit]) -> (Sign, BigUint) {
// 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)];
match cmp_slice(a, b) {
Greater => {
let mut a: SmallVec<[BigDigit; VEC_SIZE]> = a.into();
sub2(&mut a, b);
(Plus, BigUint::new_native(a))
}
Less => {
let mut b: SmallVec<[BigDigit; VEC_SIZE]> = b.into();
sub2(&mut b, a);
(Minus, BigUint::new_native(b))
}
_ => (NoSign, Zero::zero()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use num_traits::Num;
use crate::BigInt;
#[test]
fn test_sub_sign() {
fn sub_sign_i(a: &[BigDigit], b: &[BigDigit]) -> BigInt {
let (sign, val) = sub_sign(a, b);
BigInt::from_biguint(sign, val)
}
let a = BigUint::from_str_radix("265252859812191058636308480000000", 10).unwrap();
let b = BigUint::from_str_radix("26525285981219105863630848000000", 10).unwrap();
let a_i = BigInt::from_biguint(Plus, a.clone());
let b_i = BigInt::from_biguint(Plus, b.clone());
assert_eq!(sub_sign_i(&a.data[..], &b.data[..]), &a_i - &b_i);
assert_eq!(sub_sign_i(&b.data[..], &a.data[..]), &b_i - &a_i);
}
}

3401
vendor/num-bigint-dig/src/bigint.rs vendored Normal file

File diff suppressed because it is too large Load Diff

370
vendor/num-bigint-dig/src/bigrand.rs vendored Normal file
View File

@@ -0,0 +1,370 @@
//! Randomization of big integers
use rand::Rng;
use rand::distributions::uniform::{SampleBorrow, SampleUniform, UniformSampler};
use rand::prelude::*;
use crate::BigInt;
use crate::BigUint;
use crate::Sign::*;
use crate::big_digit::BigDigit;
use crate::bigint::{into_magnitude, magnitude};
use crate::integer::Integer;
#[cfg(feature = "prime")]
use num_iter::range_step;
use num_traits::Zero;
#[cfg(feature = "prime")]
use num_traits::{FromPrimitive, ToPrimitive};
#[cfg(feature = "prime")]
use crate::prime::probably_prime;
pub trait RandBigInt {
/// Generate a random `BigUint` of the given bit size.
fn gen_biguint(&mut self, bit_size: usize) -> BigUint;
/// Generate a random BigInt of the given bit size.
fn gen_bigint(&mut self, bit_size: usize) -> BigInt;
/// Generate a random `BigUint` less than the given bound. Fails
/// when the bound is zero.
fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint;
/// 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.
fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint;
/// 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 + ?Sized> RandBigInt for R {
fn gen_biguint(&mut self, bit_size: usize) -> BigUint {
use super::big_digit::BITS;
let (digits, rem) = bit_size.div_rem(&BITS);
let mut data = smallvec![BigDigit::default(); digits + (rem > 0) as usize];
// `fill` is faster than many `gen::<u32>` calls
// Internally this calls `SeedableRng` where implementors are responsible for adjusting endianness for reproducable values.
self.fill(data.as_mut_slice());
if rem > 0 {
data[digits] >>= BITS - rem;
}
BigUint::new_native(data)
}
fn gen_bigint(&mut self, bit_size: usize) -> BigInt {
loop {
// Generate a random BigUint...
let biguint = self.gen_biguint(bit_size);
// ...and then randomly assign it a Sign...
let sign = if biguint.is_zero() {
// ...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.r#gen() {
continue;
} else {
NoSign
}
} else if self.r#gen() {
Plus
} else {
Minus
};
return BigInt::from_biguint(sign, biguint);
}
}
fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint {
assert!(!bound.is_zero());
let bits = bound.bits();
loop {
let n = self.gen_biguint(bits);
if n < *bound {
return n;
}
}
}
fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint {
assert!(*lbound < *ubound);
if lbound.is_zero() {
self.gen_biguint_below(ubound)
} else {
lbound + self.gen_biguint_below(&(ubound - lbound))
}
}
fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt {
assert!(*lbound < *ubound);
if lbound.is_zero() {
BigInt::from(self.gen_biguint_below(magnitude(&ubound)))
} else if ubound.is_zero() {
lbound + BigInt::from(self.gen_biguint_below(magnitude(&lbound)))
} else {
let delta = ubound - lbound;
lbound + BigInt::from(self.gen_biguint_below(magnitude(&delta)))
}
}
}
/// The back-end implementing rand's `UniformSampler` for `BigUint`.
#[derive(Clone, Debug)]
pub struct UniformBigUint {
base: BigUint,
len: BigUint,
}
impl UniformSampler for UniformBigUint {
type X = BigUint;
#[inline]
fn new<B1, B2>(low_b: B1, high_b: B2) -> Self
where
B1: SampleBorrow<Self::X> + Sized,
B2: SampleBorrow<Self::X> + Sized,
{
let low = low_b.borrow();
let high = high_b.borrow();
assert!(low < high);
UniformBigUint {
len: high - low,
base: low.clone(),
}
}
#[inline]
fn new_inclusive<B1, B2>(low_b: B1, high_b: B2) -> Self
where
B1: SampleBorrow<Self::X> + Sized,
B2: SampleBorrow<Self::X> + Sized,
{
Self::new(low_b, high_b.borrow() + 1u32)
}
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
&self.base + rng.gen_biguint_below(&self.len)
}
#[inline]
fn sample_single<R: Rng + ?Sized, B1, B2>(low_b: B1, high_b: B2, rng: &mut R) -> Self::X
where
B1: SampleBorrow<Self::X> + Sized,
B2: SampleBorrow<Self::X> + Sized,
{
let low = low_b.borrow();
let high = high_b.borrow();
rng.gen_biguint_range(low, high)
}
}
impl SampleUniform for BigUint {
type Sampler = UniformBigUint;
}
/// The back-end implementing rand's `UniformSampler` for `BigInt`.
#[derive(Clone, Debug)]
pub struct UniformBigInt {
base: BigInt,
len: BigUint,
}
impl UniformSampler for UniformBigInt {
type X = BigInt;
#[inline]
fn new<B1, B2>(low_b: B1, high_b: B2) -> Self
where
B1: SampleBorrow<Self::X> + Sized,
B2: SampleBorrow<Self::X> + Sized,
{
let low = low_b.borrow();
let high = high_b.borrow();
assert!(low < high);
UniformBigInt {
len: into_magnitude(high - low),
base: low.clone(),
}
}
#[inline]
fn new_inclusive<B1, B2>(low_b: B1, high_b: B2) -> Self
where
B1: SampleBorrow<Self::X> + Sized,
B2: SampleBorrow<Self::X> + Sized,
{
let low = low_b.borrow();
let high = high_b.borrow();
assert!(low <= high);
Self::new(low, high + 1u32)
}
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
&self.base + BigInt::from(rng.gen_biguint_below(&self.len))
}
#[inline]
fn sample_single<R: Rng + ?Sized, B1, B2>(low_b: B1, high_b: B2, rng: &mut R) -> Self::X
where
B1: SampleBorrow<Self::X> + Sized,
B2: SampleBorrow<Self::X> + Sized,
{
let low = low_b.borrow();
let high = high_b.borrow();
rng.gen_bigint_range(low, high)
}
}
impl SampleUniform for BigInt {
type Sampler = UniformBigInt;
}
/// A random distribution for `BigUint` and `BigInt` values of a particular bit size.
#[derive(Clone, Copy, Debug)]
pub struct RandomBits {
bits: usize,
}
impl RandomBits {
#[inline]
pub fn new(bits: usize) -> RandomBits {
RandomBits { bits }
}
}
impl Distribution<BigUint> for RandomBits {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> BigUint {
rng.gen_biguint(self.bits)
}
}
impl Distribution<BigInt> for RandomBits {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> BigInt {
rng.gen_bigint(self.bits)
}
}
/// A generic trait for generating random primes.
///
/// *Warning*: This is highly dependend on the provided random number generator,
/// to provide actually random primes.
///
/// # Example
#[cfg_attr(feature = "std", doc = " ```")]
#[cfg_attr(not(feature = "std"), doc = " ```ignore")]
/// extern crate rand;
/// extern crate num_bigint_dig as num_bigint;
///
/// use rand::thread_rng;
/// use num_bigint::RandPrime;
///
/// let mut rng = thread_rng();
/// let p = rng.gen_prime(1024);
/// assert_eq!(p.bits(), 1024);
/// ```
///
#[cfg(feature = "prime")]
pub trait RandPrime {
/// Generate a random prime number with as many bits as given.
fn gen_prime(&mut self, bits: usize) -> BigUint;
}
/// A list of small, prime numbers that allows us to rapidly
/// exclude some fraction of composite candidates when searching for a random
/// prime. This list is truncated at the point where smallPrimesProduct exceeds
/// a u64. It does not include two because we ensure that the candidates are
/// odd by construction.
#[cfg(feature = "prime")]
const SMALL_PRIMES: [u8; 15] = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53];
#[cfg(feature = "prime")]
lazy_static! {
/// The product of the values in SMALL_PRIMES and allows us
/// to reduce a candidate prime by this number and then determine whether it's
/// coprime to all the elements of SMALL_PRIMES without further BigUint
/// operations.
static ref SMALL_PRIMES_PRODUCT: BigUint = BigUint::from_u64(16_294_579_238_595_022_365).unwrap();
}
#[cfg(feature = "prime")]
impl<R: Rng + ?Sized> RandPrime for R {
fn gen_prime(&mut self, bit_size: usize) -> BigUint {
if bit_size < 2 {
panic!("prime size must be at least 2-bit");
}
let mut b = bit_size % 8;
if b == 0 {
b = 8;
}
let bytes_len = (bit_size + 7) / 8;
let mut bytes = alloc::vec![0u8; bytes_len];
loop {
self.fill_bytes(&mut bytes);
// Clear bits in the first byte to make sure the candidate has a size <= bits.
bytes[0] &= ((1u32 << (b as u32)) - 1) as u8;
// Don't let the value be too small, i.e, set the most significant two bits.
// Setting the top two bits, rather than just the top bit,
// means that when two of these values are multiplied together,
// the result isn't ever one bit short.
if b >= 2 {
bytes[0] |= 3u8.wrapping_shl(b as u32 - 2);
} else {
// Here b==1, because b cannot be zero.
bytes[0] |= 1;
if bytes_len > 1 {
bytes[1] |= 0x80;
}
}
// Make the value odd since an even number this large certainly isn't prime.
bytes[bytes_len - 1] |= 1u8;
let mut p = BigUint::from_bytes_be(&bytes);
// must always be a u64, as the SMALL_PRIMES_PRODUCT is a u64
let rem = (&p % &*SMALL_PRIMES_PRODUCT).to_u64().unwrap();
'next: for delta in range_step(0, 1 << 20, 2) {
let m = rem + delta;
for prime in &SMALL_PRIMES {
if m % u64::from(*prime) == 0 && (bit_size > 6 || m != u64::from(*prime)) {
continue 'next;
}
}
if delta > 0 {
p += BigUint::from_u64(delta).unwrap();
}
break;
}
// There is a tiny possibility that, by adding delta, we caused
// the number to be one bit too long. Thus we check bit length here.
if p.bits() == bit_size && probably_prime(&p, 20) {
return p;
}
}
}
}

3397
vendor/num-bigint-dig/src/biguint.rs vendored Normal file

File diff suppressed because it is too large Load Diff

269
vendor/num-bigint-dig/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,269 @@
// Copyright 2018 Stichting Organism
//
// Copyright 2018 Friedel Ziegelmayer
//
// 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`).
//!
//! A `BigUint` is represented as a vector of `BigDigit`s.
//! 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
//! extern crate num_bigint_dig as num_bigint;
//! extern crate num_traits;
//!
//! # fn main() {
//! use num_bigint::BigUint;
//! use num_traits::{Zero, One};
//! use std::mem::replace;
//!
//! // Calculate large fibonacci numbers.
//! fn fib(n: usize) -> BigUint {
//! let mut f0: BigUint = Zero::zero();
//! let mut f1: BigUint = One::one();
//! for _ in 0..n {
//! let f2 = f0 + &f1;
//! // 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:
//!
#![cfg_attr(feature = "std", doc = " ```")]
#![cfg_attr(not(feature = "std"), doc = " ```ignore")]
//!
//! # #[cfg(feature = "rand")]
//! extern crate rand;
//! extern crate num_bigint_dig as bigint;
//!
//! # #[cfg(feature = "rand")]
//! # fn main() {
//! use bigint::{ToBigInt, RandBigInt};
//!
//! let mut rng = rand::thread_rng();
//! let a = rng.gen_bigint(1000);
//!
//! let low = -10000.to_bigint().unwrap();
//! let high = 10000.to_bigint().unwrap();
//! let b = rng.gen_bigint_range(&low, &high);
//!
//! // Probably an even larger number.
//! //println!("{}", a * b);
//! # }
//!
//! # #[cfg(not(feature = "rand"))]
//! # fn main() {
//! # }
//! ```
//!
//! ## Compatibility
//!
//! The `num-bigint-dig` crate is tested for rustc 1.56 and greater.
//!
//! ## `no_std` compatibility
//!
//! This crate is compatible with `no_std` environments.
//!
//! Note however that it still requires the `alloc` crate, so the user should
//! ensure that they set a `global_allocator`.
//!
//! To use in no_std environment, add the crate as such in your `Cargo.toml`
//! file:
//!
//! ```toml
//! [dependencies]
//! num-bigint-dig = { version = "0.8", default-features=false }
//! ```
//!
//! Every features should be compatible with no_std environment, so feel free to
//! add features like `prime`, `i128`, etc...
#![doc(html_root_url = "https://docs.rs/num-bigint/0.2")]
#![no_std]
extern crate alloc;
#[cfg(feature = "std")]
extern crate std;
#[macro_use]
extern crate smallvec;
#[cfg(feature = "prime")]
#[macro_use]
extern crate lazy_static;
extern crate num_integer as integer;
use core::fmt;
#[cfg(feature = "std")]
use std::error::Error;
#[macro_use]
mod macros;
mod bigint;
mod biguint;
#[cfg(feature = "prime")]
pub mod prime;
pub mod algorithms;
pub mod traits;
pub use crate::traits::*;
#[cfg(feature = "rand")]
mod bigrand;
#[cfg(target_pointer_width = "32")]
type UsizePromotion = u32;
#[cfg(target_pointer_width = "64")]
type UsizePromotion = u64;
#[cfg(target_pointer_width = "32")]
type IsizePromotion = i32;
#[cfg(target_pointer_width = "64")]
type IsizePromotion = i64;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseBigIntError {
kind: BigIntErrorKind,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum BigIntErrorKind {
Empty,
InvalidDigit,
}
impl ParseBigIntError {
fn __description(&self) -> &str {
use crate::BigIntErrorKind::*;
match self.kind {
Empty => "cannot parse integer from empty string",
InvalidDigit => "invalid digit found in string",
}
}
fn empty() -> Self {
ParseBigIntError {
kind: BigIntErrorKind::Empty,
}
}
fn invalid() -> Self {
ParseBigIntError {
kind: BigIntErrorKind::InvalidDigit,
}
}
}
impl fmt::Display for ParseBigIntError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.__description().fmt(f)
}
}
#[cfg(feature = "std")]
impl Error for ParseBigIntError {
fn description(&self) -> &str {
self.__description()
}
}
pub use crate::biguint::BigUint;
pub use crate::biguint::IntoBigUint;
pub use crate::biguint::ToBigUint;
pub use crate::bigint::negate_sign;
pub use crate::bigint::BigInt;
pub use crate::bigint::IntoBigInt;
pub use crate::bigint::Sign;
pub use crate::bigint::ToBigInt;
#[cfg(feature = "rand")]
pub use crate::bigrand::{RandBigInt, RandomBits, UniformBigInt, UniformBigUint};
#[cfg(feature = "prime")]
pub use bigrand::RandPrime;
#[cfg(not(feature = "u64_digit"))]
pub const VEC_SIZE: usize = 8;
#[cfg(feature = "u64_digit")]
pub const VEC_SIZE: usize = 4;
mod big_digit {
/// A `BigDigit` is a `BigUint`'s composing element.
#[cfg(not(feature = "u64_digit"))]
pub type BigDigit = u32;
#[cfg(feature = "u64_digit")]
pub type BigDigit = u64;
/// A `DoubleBigDigit` is the internal type used to do the computations. Its
/// size is the double of the size of `BigDigit`.
#[cfg(not(feature = "u64_digit"))]
pub type DoubleBigDigit = u64;
#[cfg(feature = "u64_digit")]
pub type DoubleBigDigit = u128;
/// A `SignedDoubleBigDigit` is the signed version of `DoubleBigDigit`.
#[cfg(not(feature = "u64_digit"))]
pub type SignedDoubleBigDigit = i64;
#[cfg(feature = "u64_digit")]
pub type SignedDoubleBigDigit = i128;
// `DoubleBigDigit` size dependent
#[cfg(not(feature = "u64_digit"))]
pub const BITS: usize = 32;
#[cfg(feature = "u64_digit")]
pub const BITS: usize = 64;
#[cfg(not(feature = "u64_digit"))]
const LO_MASK: DoubleBigDigit = (-1i32 as DoubleBigDigit) >> BITS;
#[cfg(feature = "u64_digit")]
const LO_MASK: DoubleBigDigit = (-1i64 as DoubleBigDigit) >> BITS;
#[inline]
fn get_hi(n: DoubleBigDigit) -> BigDigit {
(n >> BITS) as BigDigit
}
#[inline]
fn get_lo(n: DoubleBigDigit) -> BigDigit {
(n & LO_MASK) as BigDigit
}
/// 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 {
(DoubleBigDigit::from(lo)) | ((DoubleBigDigit::from(hi)) << BITS)
}
}

0
vendor/num-bigint-dig/src/macro.rs vendored Normal file
View File

362
vendor/num-bigint-dig/src/macros.rs vendored Normal file
View File

@@ -0,0 +1,362 @@
#![allow(unknown_lints)] // older rustc doesn't know `unused_macros`
#![allow(unused_macros)]
macro_rules! forward_val_val_binop {
(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
$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.capacity() >= other.capacity() {
$imp::$method(self, &other)
} else {
$imp::$method(other, &self)
}
}
}
};
}
macro_rules! forward_ref_val_binop {
(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 {
// 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)
}
}
};
}
macro_rules! forward_val_ref_binop {
(impl $imp:ident for $res:ty, $method:ident) => {
impl<'a> $imp<&'a $res> for $res {
type Output = $res;
#[inline]
fn $method(self, other: &$res) -> $res {
// 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.len() >= other.len() {
$imp::$method(self.clone(), other)
} else {
$imp::$method(other.clone(), self)
}
}
}
};
}
macro_rules! forward_val_assign {
(impl $imp:ident for $res:ty, $method:ident) => {
impl $imp<$res> for $res {
#[inline]
fn $method(&mut self, other: $res) {
self.$method(&other);
}
}
};
}
macro_rules! forward_val_assign_scalar {
(impl $imp:ident for $res:ty, $scalar:ty, $method:ident) => {
impl $imp<$res> for $scalar {
#[inline]
fn $method(&mut self, other: $res) {
self.$method(&other);
}
}
};
}
macro_rules! forward_scalar_val_val_binop_commutative {
(impl $imp:ident < $scalar:ty > for $res:ty, $method:ident) => {
impl $imp<$res> for $scalar {
type Output = $res;
#[inline]
fn $method(self, other: $res) -> $res {
$imp::$method(other, self)
}
}
};
}
macro_rules! forward_scalar_val_ref_binop {
(impl $imp:ident < $scalar:ty > for $res:ty, $method:ident) => {
impl<'a> $imp<&'a $scalar> for $res {
type Output = $res;
#[inline]
fn $method(self, other: &$scalar) -> $res {
$imp::$method(self, *other)
}
}
impl<'a> $imp<$res> for &'a $scalar {
type Output = $res;
#[inline]
fn $method(self, other: $res) -> $res {
$imp::$method(*self, other)
}
}
};
}
macro_rules! forward_scalar_ref_val_binop {
(impl $imp:ident < $scalar:ty > for $res:ty, $method:ident) => {
impl<'a> $imp<$scalar> for &'a $res {
type Output = $res;
#[inline]
fn $method(self, other: $scalar) -> $res {
$imp::$method(self.clone(), other)
}
}
impl<'a> $imp<&'a $res> for $scalar {
type Output = $res;
#[inline]
fn $method(self, other: &$res) -> $res {
$imp::$method(self, other.clone())
}
}
};
}
macro_rules! forward_scalar_ref_ref_binop {
(impl $imp:ident < $scalar:ty > for $res:ty, $method:ident) => {
impl<'a, 'b> $imp<&'b $scalar> for &'a $res {
type Output = $res;
#[inline]
fn $method(self, other: &$scalar) -> $res {
$imp::$method(self.clone(), *other)
}
}
impl<'a, 'b> $imp<&'a $res> for &'b $scalar {
type Output = $res;
#[inline]
fn $method(self, other: &$res) -> $res {
$imp::$method(*self, other.clone())
}
}
};
}
macro_rules! promote_scalars {
(impl $imp:ident<$promo:ty> for $res:ty, $method:ident, $( $scalar:ty ),*) => {
$(
forward_all_scalar_binop_to_val_val!(impl $imp<$scalar> for $res, $method);
impl $imp<$scalar> for $res {
type Output = $res;
#[inline]
fn $method(self, other: $scalar) -> $res {
$imp::$method(self, other as $promo)
}
}
impl $imp<$res> for $scalar {
type Output = $res;
#[inline]
fn $method(self, other: $res) -> $res {
$imp::$method(self as $promo, other)
}
}
)*
}
}
macro_rules! promote_scalars_assign {
(impl $imp:ident<$promo:ty> for $res:ty, $method:ident, $( $scalar:ty ),*) => {
$(
impl $imp<$scalar> for $res {
#[inline]
fn $method(&mut self, other: $scalar) {
self.$method(other as $promo);
}
}
)*
}
}
macro_rules! promote_unsigned_scalars {
(impl $imp:ident for $res:ty, $method:ident) => {
promote_scalars!(impl $imp<u32> for $res, $method, u8, u16);
promote_scalars!(impl $imp<UsizePromotion> for $res, $method, usize);
}
}
macro_rules! promote_unsigned_scalars_assign {
(impl $imp:ident for $res:ty, $method:ident) => {
promote_scalars_assign!(impl $imp<u32> for $res, $method, u8, u16);
promote_scalars_assign!(impl $imp<UsizePromotion> for $res, $method, usize);
}
}
macro_rules! promote_signed_scalars {
(impl $imp:ident for $res:ty, $method:ident) => {
promote_scalars!(impl $imp<i32> for $res, $method, i8, i16);
promote_scalars!(impl $imp<IsizePromotion> for $res, $method, isize);
}
}
macro_rules! promote_signed_scalars_assign {
(impl $imp:ident for $res:ty, $method:ident) => {
promote_scalars_assign!(impl $imp<i32> for $res, $method, i8, i16);
promote_scalars_assign!(impl $imp<UsizePromotion> for $res, $method, isize);
}
}
// Forward everything to ref-ref, when reusing storage is not helpful
macro_rules! forward_all_binop_to_ref_ref {
(impl $imp:ident for $res:ty, $method:ident) => {
forward_val_val_binop!(impl $imp for $res, $method);
forward_val_ref_binop!(impl $imp for $res, $method);
forward_ref_val_binop!(impl $imp for $res, $method);
};
}
// 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);
};
}
// 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);
};
}
macro_rules! forward_all_scalar_binop_to_val_val {
(impl $imp:ident<$scalar:ty> for $res:ty, $method:ident) => {
forward_scalar_val_ref_binop!(impl $imp<$scalar> for $res, $method);
forward_scalar_ref_val_binop!(impl $imp<$scalar> for $res, $method);
forward_scalar_ref_ref_binop!(impl $imp<$scalar> for $res, $method);
}
}
macro_rules! forward_all_scalar_binop_to_val_val_commutative {
(impl $imp:ident<$scalar:ty> for $res:ty, $method:ident) => {
forward_scalar_val_val_binop_commutative!(impl $imp<$scalar> for $res, $method);
forward_all_scalar_binop_to_val_val!(impl $imp<$scalar> for $res, $method);
}
}
macro_rules! promote_all_scalars {
(impl $imp:ident for $res:ty, $method:ident) => {
promote_unsigned_scalars!(impl $imp for $res, $method);
promote_signed_scalars!(impl $imp for $res, $method);
}
}
macro_rules! promote_all_scalars_assign {
(impl $imp:ident for $res:ty, $method:ident) => {
promote_unsigned_scalars_assign!(impl $imp for $res, $method);
promote_signed_scalars_assign!(impl $imp for $res, $method);
}
}
macro_rules! impl_sum_iter_type {
($res:ty) => {
impl<T> Sum<T> for $res
where
$res: Add<T, Output = $res>,
{
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = T>,
{
iter.fold(Zero::zero(), <$res>::add)
}
}
};
}
macro_rules! impl_product_iter_type {
($res:ty) => {
impl<T> Product<T> for $res
where
$res: Mul<T, Output = $res>,
{
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = T>,
{
iter.fold(One::one(), <$res>::mul)
}
}
};
}

225
vendor/num-bigint-dig/src/monty.rs vendored Normal file
View File

@@ -0,0 +1,225 @@
#![allow(clippy::many_single_char_names)]
use alloc::vec::Vec;
use core::ops::Shl;
use num_traits::{One, Zero};
use crate::big_digit::{self, BigDigit, DoubleBigDigit, SignedDoubleBigDigit};
use crate::biguint::BigUint;
struct MontyReducer {
n0inv: BigDigit,
}
// k0 = -m**-1 mod 2**BITS. Algorithm from: Dumas, J.G. "On NewtonRaphson
// Iteration for Multiplicative Inverses Modulo Prime Powers".
fn inv_mod_alt(b: BigDigit) -> BigDigit {
assert_ne!(b & 1, 0);
let mut k0 = 2 - b as SignedDoubleBigDigit;
let mut t = (b - 1) as SignedDoubleBigDigit;
let mut i = 1;
while i < big_digit::BITS {
t = t.wrapping_mul(t);
k0 = k0.wrapping_mul(t + 1);
i <<= 1;
}
-k0 as BigDigit
}
impl MontyReducer {
fn new(n: &BigUint) -> Self {
let n0inv = inv_mod_alt(n.data[0]);
MontyReducer { n0inv }
}
}
/// Computes z mod m = x * y * 2 ** (-n*_W) mod m
/// assuming k = -1/m mod 2**_W
/// See Gueron, "Efficient Software Implementations of Modular Exponentiation".
/// https://eprint.iacr.org/2011/239.pdf
/// In the terminology of that paper, this is an "Almost Montgomery Multiplication":
/// x and y are required to satisfy 0 <= z < 2**(n*_W) and then the result
/// z is guaranteed to satisfy 0 <= z < 2**(n*_W), but it may not be < m.
fn montgomery(z: &mut BigUint, x: &BigUint, y: &BigUint, m: &BigUint, k: BigDigit, n: usize) {
// This code assumes x, y, m are all the same length, n.
// (required by addMulVVW and the for loop).
// It also assumes that x, y are already reduced mod m,
// or else the result will not be properly reduced.
assert!(
x.data.len() == n && y.data.len() == n && m.data.len() == n,
"{:?} {:?} {:?} {}",
x,
y,
m,
n
);
z.data.clear();
z.data.resize(n * 2, 0);
let mut c: BigDigit = 0;
for i in 0..n {
let c2 = add_mul_vvw(&mut z.data[i..n + i], &x.data, y.data[i]);
let t = z.data[i].wrapping_mul(k);
let c3 = add_mul_vvw(&mut z.data[i..n + i], &m.data, t);
let cx = c.wrapping_add(c2);
let cy = cx.wrapping_add(c3);
z.data[n + i] = cy;
c = if cx < c2 || cy < c3 { 1 } else { 0 };
}
if c == 0 {
let (first, second) = z.data.split_at_mut(n);
first.swap_with_slice(&mut second[..]);
} else {
let (mut first, second) = z.data.split_at_mut(n);
sub_vv(&mut first, &second, &m.data);
}
z.data.truncate(n);
}
#[inline]
fn add_mul_vvw(z: &mut [BigDigit], x: &[BigDigit], y: BigDigit) -> BigDigit {
let mut c = 0;
for (zi, xi) in z.iter_mut().zip(x.iter()) {
let (z1, z0) = mul_add_www(*xi, y, *zi);
let (c_, zi_) = add_ww(z0, c, 0);
*zi = zi_;
c = c_ + z1;
}
c
}
/// The resulting carry c is either 0 or 1.
#[inline]
fn sub_vv(z: &mut [BigDigit], x: &[BigDigit], y: &[BigDigit]) -> BigDigit {
let mut c = 0;
for (i, (xi, yi)) in x.iter().zip(y.iter()).enumerate().take(z.len()) {
let zi = xi.wrapping_sub(*yi).wrapping_sub(c);
z[i] = zi;
// see "Hacker's Delight", section 2-12 (overflow detection)
c = ((yi & !xi) | ((yi | !xi) & zi)) >> (big_digit::BITS - 1)
}
c
}
/// z1<<_W + z0 = x+y+c, with c == 0 or 1
#[inline]
fn add_ww(x: BigDigit, y: BigDigit, c: BigDigit) -> (BigDigit, BigDigit) {
let yc = y.wrapping_add(c);
let z0 = x.wrapping_add(yc);
let z1 = if z0 < x || yc < y { 1 } else { 0 };
(z1, z0)
}
/// z1 << _W + z0 = x * y + c
#[inline]
fn mul_add_www(x: BigDigit, y: BigDigit, c: BigDigit) -> (BigDigit, BigDigit) {
let z = x as DoubleBigDigit * y as DoubleBigDigit + c as DoubleBigDigit;
((z >> big_digit::BITS) as BigDigit, z as BigDigit)
}
/// Calculates x ** y mod m using a fixed, 4-bit window.
pub fn monty_modpow(x: &BigUint, y: &BigUint, m: &BigUint) -> BigUint {
assert!(m.data[0] & 1 == 1);
let mr = MontyReducer::new(m);
let num_words = m.data.len();
let mut x = x.clone();
// We want the lengths of x and m to be equal.
// It is OK if x >= m as long as len(x) == len(m).
if x.data.len() > num_words {
x %= m;
// Note: now len(x) <= numWords, not guaranteed ==.
}
if x.data.len() < num_words {
x.data.resize(num_words, 0);
}
// rr = 2**(2*_W*len(m)) mod m
let mut rr = BigUint::one();
rr = (rr.shl(2 * num_words * big_digit::BITS)) % m;
if rr.data.len() < num_words {
rr.data.resize(num_words, 0);
}
// one = 1, with equal length to that of m
let mut one = BigUint::one();
one.data.resize(num_words, 0);
let n = 4;
// powers[i] contains x^i
let mut powers = Vec::with_capacity(1 << n);
let mut v1 = BigUint::zero();
montgomery(&mut v1, &one, &rr, m, mr.n0inv, num_words);
powers.push(v1);
let mut v2 = BigUint::zero();
montgomery(&mut v2, &x, &rr, m, mr.n0inv, num_words);
powers.push(v2);
for i in 2..1 << n {
let mut r = BigUint::zero();
montgomery(&mut r, &powers[i - 1], &powers[1], m, mr.n0inv, num_words);
powers.push(r);
}
// initialize z = 1 (Montgomery 1)
let mut z = powers[0].clone();
z.data.resize(num_words, 0);
let mut zz = BigUint::zero();
zz.data.resize(num_words, 0);
// same windowed exponent, but with Montgomery multiplications
for i in (0..y.data.len()).rev() {
let mut yi = y.data[i];
let mut j = 0;
while j < big_digit::BITS {
if i != y.data.len() - 1 || j != 0 {
montgomery(&mut zz, &z, &z, m, mr.n0inv, num_words);
montgomery(&mut z, &zz, &zz, m, mr.n0inv, num_words);
montgomery(&mut zz, &z, &z, m, mr.n0inv, num_words);
montgomery(&mut z, &zz, &zz, m, mr.n0inv, num_words);
}
montgomery(
&mut zz,
&z,
&powers[(yi >> (big_digit::BITS - n)) as usize],
m,
mr.n0inv,
num_words,
);
core::mem::swap(&mut z, &mut zz);
yi <<= n;
j += n;
}
}
// convert to regular number
montgomery(&mut zz, &z, &one, m, mr.n0inv, num_words);
zz.normalize();
// One last reduction, just in case.
// See golang.org/issue/13907.
if &zz >= m {
// Common case is m has high bit set; in that case,
// since zz is the same length as m, there can be just
// one multiple of m to remove. Just subtract.
// We think that the subtract should be sufficient in general,
// so do that unconditionally, but double-check,
// in case our beliefs are wrong.
// The div is not expected to be reached.
zz -= m;
if &zz >= m {
zz %= m;
}
}
zz.normalize();
zz
}

673
vendor/num-bigint-dig/src/prime.rs vendored Normal file
View File

@@ -0,0 +1,673 @@
// https://github.com/RustCrypto/RSA/blob/master/src/prime.rs
//! Implements probabilistic prime checkers.
use alloc::vec;
use integer::Integer;
use num_traits::{FromPrimitive, One, ToPrimitive, Zero};
use rand::rngs::StdRng;
use rand::SeedableRng;
use crate::algorithms::jacobi;
use crate::big_digit;
use crate::bigrand::RandBigInt;
use crate::Sign::Plus;
use crate::{BigInt, BigUint, IntoBigUint};
lazy_static! {
pub(crate) static ref BIG_1: BigUint = BigUint::one();
pub(crate) static ref BIG_2: BigUint = BigUint::from_u64(2).unwrap();
pub(crate) static ref BIG_3: BigUint = BigUint::from_u64(3).unwrap();
pub(crate) static ref BIG_64: BigUint = BigUint::from_u64(64).unwrap();
}
const PRIMES_A: u64 = 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 37;
const PRIMES_B: u64 = 29 * 31 * 41 * 43 * 47 * 53;
/// Records the primes < 64.
const PRIME_BIT_MASK: u64 = 1 << 2
| 1 << 3
| 1 << 5
| 1 << 7
| 1 << 11
| 1 << 13
| 1 << 17
| 1 << 19
| 1 << 23
| 1 << 29
| 1 << 31
| 1 << 37
| 1 << 41
| 1 << 43
| 1 << 47
| 1 << 53
| 1 << 59
| 1 << 61;
/// ProbablyPrime reports whether x is probably prime,
/// applying the Miller-Rabin test with n pseudorandomly chosen bases
/// as well as a Baillie-PSW test.
///
/// If x is prime, ProbablyPrime returns true.
/// If x is chosen randomly and not prime, ProbablyPrime probably returns false.
/// The probability of returning true for a randomly chosen non-prime is at most ¼ⁿ.
///
/// ProbablyPrime is 100% accurate for inputs less than 2⁶⁴.
/// See Menezes et al., Handbook of Applied Cryptography, 1997, pp. 145-149,
/// and FIPS 186-4 Appendix F for further discussion of the error probabilities.
///
/// ProbablyPrime is not suitable for judging primes that an adversary may
/// have crafted to fool the test.
///
/// This is a port of `ProbablyPrime` from the go std lib.
pub fn probably_prime(x: &BigUint, n: usize) -> bool {
if x.is_zero() {
return false;
}
if x < &*BIG_64 {
return (PRIME_BIT_MASK & (1 << x.to_u64().unwrap())) != 0;
}
if x.is_even() {
return false;
}
let r_a = &(x % PRIMES_A);
let r_b = &(x % PRIMES_B);
if (r_a % 3u32).is_zero()
|| (r_a % 5u32).is_zero()
|| (r_a % 7u32).is_zero()
|| (r_a % 11u32).is_zero()
|| (r_a % 13u32).is_zero()
|| (r_a % 17u32).is_zero()
|| (r_a % 19u32).is_zero()
|| (r_a % 23u32).is_zero()
|| (r_a % 37u32).is_zero()
|| (r_b % 29u32).is_zero()
|| (r_b % 31u32).is_zero()
|| (r_b % 41u32).is_zero()
|| (r_b % 43u32).is_zero()
|| (r_b % 47u32).is_zero()
|| (r_b % 53u32).is_zero()
{
return false;
}
probably_prime_miller_rabin(x, n + 1, true) && probably_prime_lucas(x)
}
const NUMBER_OF_PRIMES: usize = 127;
const PRIME_GAP: [u64; 167] = [
2, 2, 4, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 14, 4, 6,
2, 10, 2, 6, 6, 4, 6, 6, 2, 10, 2, 4, 2, 12, 12, 4, 2, 4, 6, 2, 10, 6, 6, 6, 2, 6, 4, 2, 10,
14, 4, 2, 4, 14, 6, 10, 2, 4, 6, 8, 6, 6, 4, 6, 8, 4, 8, 10, 2, 10, 2, 6, 4, 6, 8, 4, 2, 4, 12,
8, 4, 8, 4, 6, 12, 2, 18, 6, 10, 6, 6, 2, 6, 10, 6, 6, 2, 6, 6, 4, 2, 12, 10, 2, 4, 6, 6, 2,
12, 4, 6, 8, 10, 8, 10, 8, 6, 6, 4, 8, 6, 4, 8, 4, 14, 10, 12, 2, 10, 2, 4, 2, 10, 14, 4, 2, 4,
14, 4, 2, 4, 20, 4, 8, 10, 8, 4, 6, 6, 14, 4, 6, 6, 8, 6, 12,
];
const INCR_LIMIT: usize = 0x10000;
/// Calculate the next larger prime, given a starting number `n`.
pub fn next_prime(n: &BigUint) -> BigUint {
if n < &*BIG_2 {
return 2u32.into_biguint().unwrap();
}
// We want something larger than our current number.
let mut res = n + &*BIG_1;
// Ensure we are odd.
res |= &*BIG_1;
// Handle values up to 7.
if let Some(val) = res.to_u64() {
if val < 7 {
return res;
}
}
let nbits = res.bits();
let prime_limit = if nbits / 2 >= NUMBER_OF_PRIMES {
NUMBER_OF_PRIMES - 1
} else {
nbits / 2
};
// Compute the residues modulo small odd primes
let mut moduli = vec![BigUint::zero(); prime_limit];
'outer: loop {
let mut prime = 3;
for i in 0..prime_limit {
moduli[i] = &res % prime;
prime += PRIME_GAP[i];
}
// Check residues
let mut difference: usize = 0;
for incr in (0..INCR_LIMIT as u64).step_by(2) {
let mut prime: u64 = 3;
let mut cancel = false;
for i in 0..prime_limit {
let r = (&moduli[i] + incr) % prime;
prime += PRIME_GAP[i];
if r.is_zero() {
cancel = true;
break;
}
}
if !cancel {
res += difference;
difference = 0;
if probably_prime(&res, 20) {
break 'outer;
}
}
difference += 2;
}
res += difference;
}
res
}
/// Reports whether n passes reps rounds of the Miller-Rabin primality test, using pseudo-randomly chosen bases.
/// If `force2` is true, one of the rounds is forced to use base 2.
///
/// See Handbook of Applied Cryptography, p. 139, Algorithm 4.24.
pub fn probably_prime_miller_rabin(n: &BigUint, reps: usize, force2: bool) -> bool {
// println!("miller-rabin: {}", n);
let nm1 = n - &*BIG_1;
// determine q, k such that nm1 = q << k
let k = nm1.trailing_zeros().unwrap() as usize;
let q = &nm1 >> k;
let nm3 = n - &*BIG_2;
let mut rng = StdRng::seed_from_u64(n.get_limb(0) as u64);
'nextrandom: for i in 0..reps {
let x = if i == reps - 1 && force2 {
BIG_2.clone()
} else {
rng.gen_biguint_below(&nm3) + &*BIG_2
};
let mut y = x.modpow(&q, n);
if y.is_one() || y == nm1 {
continue;
}
for _ in 1..k {
y = y.modpow(&*BIG_2, n);
if y == nm1 {
continue 'nextrandom;
}
if y.is_one() {
return false;
}
}
return false;
}
true
}
/// Reports whether n passes the "almost extra strong" Lucas probable prime test,
/// using Baillie-OEIS parameter selection. This corresponds to "AESLPSP" on Jacobsen's tables (link below).
/// The combination of this test and a Miller-Rabin/Fermat test with base 2 gives a Baillie-PSW test.
///
///
/// References:
///
/// Baillie and Wagstaff, "Lucas Pseudoprimes", Mathematics of Computation 35(152),
/// October 1980, pp. 1391-1417, especially page 1401.
/// http://www.ams.org/journals/mcom/1980-35-152/S0025-5718-1980-0583518-6/S0025-5718-1980-0583518-6.pdf
///
/// Grantham, "Frobenius Pseudoprimes", Mathematics of Computation 70(234),
/// March 2000, pp. 873-891.
/// http://www.ams.org/journals/mcom/2001-70-234/S0025-5718-00-01197-2/S0025-5718-00-01197-2.pdf
///
/// Baillie, "Extra strong Lucas pseudoprimes", OEIS A217719, https://oeis.org/A217719.
///
/// Jacobsen, "Pseudoprime Statistics, Tables, and Data", http://ntheory.org/pseudoprimes.html.
///
/// Nicely, "The Baillie-PSW Primality Test", http://www.trnicely.net/misc/bpsw.html.
/// (Note that Nicely's definition of the "extra strong" test gives the wrong Jacobi condition,
/// as pointed out by Jacobsen.)
///
/// Crandall and Pomerance, Prime Numbers: A Computational Perspective, 2nd ed.
/// Springer, 2005.
pub fn probably_prime_lucas(n: &BigUint) -> bool {
// println!("lucas: {}", n);
// Discard 0, 1.
if n.is_zero() || n.is_one() {
return false;
}
// Two is the only even prime.
if n.to_u64() == Some(2) {
return false;
}
// Baillie-OEIS "method C" for choosing D, P, Q,
// as in https://oeis.org/A217719/a217719.txt:
// try increasing P ≥ 3 such that D = P² - 4 (so Q = 1)
// until Jacobi(D, n) = -1.
// The search is expected to succeed for non-square n after just a few trials.
// After more than expected failures, check whether n is square
// (which would cause Jacobi(D, n) = 1 for all D not dividing n).
let mut p = 3u64;
let n_int = BigInt::from_biguint(Plus, n.clone());
loop {
if p > 10000 {
// This is widely believed to be impossible.
// If we get a report, we'll want the exact number n.
panic!("internal error: cannot find (D/n) = -1 for {:?}", n)
}
let d_int = BigInt::from_u64(p * p - 4).unwrap();
let j = jacobi(&d_int, &n_int);
if j == -1 {
break;
}
if j == 0 {
// d = p²-4 = (p-2)(p+2).
// If (d/n) == 0 then d shares a prime factor with n.
// Since the loop proceeds in increasing p and starts with p-2==1,
// the shared prime factor must be p+2.
// If p+2 == n, then n is prime; otherwise p+2 is a proper factor of n.
return n_int.to_i64() == Some(p as i64 + 2);
}
if p == 40 {
// We'll never find (d/n) = -1 if n is a square.
// If n is a non-square we expect to find a d in just a few attempts on average.
// After 40 attempts, take a moment to check if n is indeed a square.
let t1 = n.sqrt();
let t1 = &t1 * &t1;
if &t1 == n {
return false;
}
}
p += 1;
}
// Grantham definition of "extra strong Lucas pseudoprime", after Thm 2.3 on p. 876
// (D, P, Q above have become Δ, b, 1):
//
// Let U_n = U_n(b, 1), V_n = V_n(b, 1), and Δ = b²-4.
// An extra strong Lucas pseudoprime to base b is a composite n = 2^r s + Jacobi(Δ, n),
// where s is odd and gcd(n, 2*Δ) = 1, such that either (i) U_s ≡ 0 mod n and V_s ≡ ±2 mod n,
// or (ii) V_{2^t s} ≡ 0 mod n for some 0 ≤ t < r-1.
//
// We know gcd(n, Δ) = 1 or else we'd have found Jacobi(d, n) == 0 above.
// We know gcd(n, 2) = 1 because n is odd.
//
// Arrange s = (n - Jacobi(Δ, n)) / 2^r = (n+1) / 2^r.
let mut s = n + &*BIG_1;
let r = s.trailing_zeros().unwrap() as usize;
s = &s >> r;
let nm2 = n - &*BIG_2; // n - 2
// We apply the "almost extra strong" test, which checks the above conditions
// except for U_s ≡ 0 mod n, which allows us to avoid computing any U_k values.
// Jacobsen points out that maybe we should just do the full extra strong test:
// "It is also possible to recover U_n using Crandall and Pomerance equation 3.13:
// U_n = D^-1 (2V_{n+1} - PV_n) allowing us to run the full extra-strong test
// at the cost of a single modular inversion. This computation is easy and fast in GMP,
// so we can get the full extra-strong test at essentially the same performance as the
// almost extra strong test."
// Compute Lucas sequence V_s(b, 1), where:
//
// V(0) = 2
// V(1) = P
// V(k) = P V(k-1) - Q V(k-2).
//
// (Remember that due to method C above, P = b, Q = 1.)
//
// In general V(k) = α^k + β^k, where α and β are roots of x² - Px + Q.
// Crandall and Pomerance (p.147) observe that for 0 ≤ j ≤ k,
//
// V(j+k) = V(j)V(k) - V(k-j).
//
// So in particular, to quickly double the subscript:
//
// V(2k) = V(k)² - 2
// V(2k+1) = V(k) V(k+1) - P
//
// We can therefore start with k=0 and build up to k=s in log₂(s) steps.
let mut vk = BIG_2.clone();
let mut vk1 = BigUint::from_u64(p).unwrap();
for i in (0..s.bits()).rev() {
if is_bit_set(&s, i) {
// k' = 2k+1
// V(k') = V(2k+1) = V(k) V(k+1) - P
let t1 = (&vk * &vk1) + n - p;
vk = &t1 % n;
// V(k'+1) = V(2k+2) = V(k+1)² - 2
let t1 = (&vk1 * &vk1) + &nm2;
vk1 = &t1 % n;
} else {
// k' = 2k
// V(k'+1) = V(2k+1) = V(k) V(k+1) - P
let t1 = (&vk * &vk1) + n - p;
vk1 = &t1 % n;
// V(k') = V(2k) = V(k)² - 2
let t1 = (&vk * &vk) + &nm2;
vk = &t1 % n;
}
}
// Now k=s, so vk = V(s). Check V(s) ≡ ±2 (mod n).
if vk.to_u64() == Some(2) || vk == nm2 {
// Check U(s) ≡ 0.
// As suggested by Jacobsen, apply Crandall and Pomerance equation 3.13:
//
// U(k) = D⁻¹ (2 V(k+1) - P V(k))
//
// Since we are checking for U(k) == 0 it suffices to check 2 V(k+1) == P V(k) mod n,
// or P V(k) - 2 V(k+1) == 0 mod n.
let mut t1 = &vk * p;
let mut t2 = &vk1 << 1;
if t1 < t2 {
core::mem::swap(&mut t1, &mut t2);
}
t1 -= t2;
if (t1 % n).is_zero() {
return true;
}
}
// Check V(2^t s) ≡ 0 mod n for some 0 ≤ t < r-1.
for _ in 0..r - 1 {
if vk.is_zero() {
return true;
}
// Optimization: V(k) = 2 is a fixed point for V(k') = V(k)² - 2,
// so if V(k) = 2, we can stop: we will never find a future V(k) == 0.
if vk.to_u64() == Some(2) {
return false;
}
// k' = 2k
// V(k') = V(2k) = V(k)² - 2
let t1 = (&vk * &vk) - &*BIG_2;
vk = &t1 % n;
}
false
}
/// Checks if the i-th bit is set
#[inline]
fn is_bit_set(x: &BigUint, i: usize) -> bool {
get_bit(x, i) == 1
}
/// Returns the i-th bit.
#[inline]
fn get_bit(x: &BigUint, i: usize) -> u8 {
let j = i / big_digit::BITS;
// if is out of range of the set words, it is always false.
if i >= x.bits() {
return 0;
}
(x.get_limb(j) >> (i % big_digit::BITS) & 1) as u8
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec::Vec;
// use RandBigInt;
use crate::biguint::ToBigUint;
lazy_static! {
static ref PRIMES: Vec<&'static str> = vec![
"2",
"3",
"5",
"7",
"11",
"13756265695458089029",
"13496181268022124907",
"10953742525620032441",
"17908251027575790097",
// https://golang.org/issue/638
"18699199384836356663",
"98920366548084643601728869055592650835572950932266967461790948584315647051443",
"94560208308847015747498523884063394671606671904944666360068158221458669711639",
// http://primes.utm.edu/lists/small/small3.html
"449417999055441493994709297093108513015373787049558499205492347871729927573118262811508386655998299074566974373711472560655026288668094291699357843464363003144674940345912431129144354948751003607115263071543163",
"230975859993204150666423538988557839555560243929065415434980904258310530753006723857139742334640122533598517597674807096648905501653461687601339782814316124971547968912893214002992086353183070342498989426570593",
"5521712099665906221540423207019333379125265462121169655563495403888449493493629943498064604536961775110765377745550377067893607246020694972959780839151452457728855382113555867743022746090187341871655890805971735385789993",
"203956878356401977405765866929034577280193993314348263094772646453283062722701277632936616063144088173312372882677123879538709400158306567338328279154499698366071906766440037074217117805690872792848149112022286332144876183376326512083574821647933992961249917319836219304274280243803104015000563790123",
// ECC primes: http://tools.ietf.org/html/draft-ladd-safecurves-02
"3618502788666131106986593281521497120414687020801267626233049500247285301239", // Curve1174: 2^251-9
"57896044618658097711785492504343953926634992332820282019728792003956564819949", // Curve25519: 2^255-19
"9850501549098619803069760025035903451269934817616361666987073351061430442874302652853566563721228910201656997576599", // E-382: 2^382-105
"42307582002575910332922579714097346549017899709713998034217522897561970639123926132812109468141778230245837569601494931472367", // Curve41417: 2^414-17
"6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151", // E-521: 2^521-1
];
static ref COMPOSITES: Vec<&'static str> = vec![
"0",
"1",
"21284175091214687912771199898307297748211672914763848041968395774954376176754",
"6084766654921918907427900243509372380954290099172559290432744450051395395951",
"84594350493221918389213352992032324280367711247940675652888030554255915464401",
"82793403787388584738507275144194252681",
// Arnault, "Rabin-Miller Primality Test: Composite Numbers Which Pass It",
// Mathematics of Computation, 64(209) (January 1995), pp. 335-361.
"1195068768795265792518361315725116351898245581", // strong pseudoprime to prime bases 2 through 29
// strong pseudoprime to all prime bases up to 200
"8038374574536394912570796143419421081388376882875581458374889175222974273765333652186502336163960045457915042023603208766569966760987284043965408232928738791850869166857328267761771029389697739470167082304286871099974399765441448453411558724506334092790222752962294149842306881685404326457534018329786111298960644845216191652872597534901",
// Extra-strong Lucas pseudoprimes. https://oeis.org/A217719
"989",
"3239",
"5777",
"10877",
"27971",
"29681",
"30739",
"31631",
"39059",
"72389",
"73919",
"75077",
"100127",
"113573",
"125249",
"137549",
"137801",
"153931",
"155819",
"161027",
"162133",
"189419",
"218321",
"231703",
"249331",
"370229",
"429479",
"430127",
"459191",
"473891",
"480689",
"600059",
"621781",
"632249",
"635627",
"3673744903",
"3281593591",
"2385076987",
"2738053141",
"2009621503",
"1502682721",
"255866131",
"117987841",
"587861",
"6368689",
"8725753",
"80579735209",
"105919633",
];
// Test Cases from #51
static ref ISSUE_51: Vec<&'static str> = vec![
"1579751",
"1884791",
"3818929",
"4080359",
"4145951",
];
}
#[test]
fn test_primes() {
for prime in PRIMES.iter() {
let p = BigUint::parse_bytes(prime.as_bytes(), 10).unwrap();
for i in [0, 1, 20].iter() {
assert!(
probably_prime(&p, *i as usize),
"{} is a prime ({})",
prime,
i,
);
}
}
}
#[test]
fn test_composites() {
for comp in COMPOSITES.iter() {
let p = BigUint::parse_bytes(comp.as_bytes(), 10).unwrap();
for i in [0, 1, 20].iter() {
assert!(
!probably_prime(&p, *i as usize),
"{} is a composite ({})",
comp,
i,
);
}
}
}
#[test]
fn test_issue_51() {
for num in ISSUE_51.iter() {
let p = BigUint::parse_bytes(num.as_bytes(), 10).unwrap();
assert!(probably_prime(&p, 20), "{} is a prime number", num);
}
}
macro_rules! test_pseudo_primes {
($name:ident, $cond:expr, $want:expr) => {
#[test]
fn $name() {
let mut i = 3;
let mut want = $want;
while i < 100000 {
let n = BigUint::from_u64(i).unwrap();
let pseudo = $cond(&n);
if pseudo && (want.is_empty() || i != want[0]) {
panic!("cond({}) = true, want false", i);
} else if !pseudo && !want.is_empty() && i == want[0] {
panic!("cond({}) = false, want true", i);
}
if !want.is_empty() && i == want[0] {
want = want[1..].to_vec();
}
i += 2;
}
if !want.is_empty() {
panic!("forgot to test: {:?}", want);
}
}
};
}
test_pseudo_primes!(
test_probably_prime_miller_rabin,
|n| probably_prime_miller_rabin(n, 1, true) && !probably_prime_lucas(n),
vec![
2047, 3277, 4033, 4681, 8321, 15841, 29341, 42799, 49141, 52633, 65281, 74665, 80581,
85489, 88357, 90751,
]
);
test_pseudo_primes!(
test_probably_prime_lucas,
|n| probably_prime_lucas(n) && !probably_prime_miller_rabin(n, 1, true),
vec![989, 3239, 5777, 10877, 27971, 29681, 30739, 31631, 39059, 72389, 73919, 75077,]
);
#[test]
fn test_bit_set() {
let v = &vec![0b10101001];
let num = BigUint::from_slice(&v);
assert!(is_bit_set(&num, 0));
assert!(!is_bit_set(&num, 1));
assert!(!is_bit_set(&num, 2));
assert!(is_bit_set(&num, 3));
assert!(!is_bit_set(&num, 4));
assert!(is_bit_set(&num, 5));
assert!(!is_bit_set(&num, 6));
assert!(is_bit_set(&num, 7));
}
#[test]
fn test_next_prime_basics() {
let primes1 = (0..2048u32)
.map(|i| next_prime(&i.to_biguint().unwrap()))
.collect::<Vec<_>>();
let primes2 = (0..2048u32)
.map(|i| {
let i = i.to_biguint().unwrap();
let p = next_prime(&i);
assert!(&p > &i);
p
})
.collect::<Vec<_>>();
for (p1, p2) in primes1.iter().zip(&primes2) {
assert_eq!(p1, p2);
assert!(probably_prime(p1, 25));
}
}
#[test]
fn test_next_prime_bug_44() {
let i = 1032989.to_biguint().unwrap();
let next = next_prime(&i);
assert_eq!(1033001.to_biguint().unwrap(), next);
}
}

24
vendor/num-bigint-dig/src/traits.rs vendored Normal file
View File

@@ -0,0 +1,24 @@
use crate::BigInt;
/// Generic trait to implement modular inverse.
pub trait ModInverse<R: Sized>: Sized {
type Output: Sized;
/// Function to calculate the [modular multiplicative
/// inverse](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse) of an integer *a* modulo *m*.
///
/// TODO: references
/// Returns the modular inverse of `self`.
/// If none exists it returns `None`.
fn mod_inverse(self, m: R) -> Option<Self::Output>;
}
/// Generic trait to implement extended GCD.
/// Calculates the extended eucledian algorithm.
/// See https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm for details.
/// The returned values are
/// - greatest common divisor (1)
/// - Bezout coefficients (2)
pub trait ExtendedGcd<R: Sized>: Sized {
fn extended_gcd(self, other: R) -> (BigInt, BigInt, BigInt);
}