algorithms.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. use std::borrow::Cow;
  2. use std::cmp;
  3. use std::cmp::Ordering::{self, Less, Greater, Equal};
  4. use std::iter::repeat;
  5. use std::mem;
  6. use traits;
  7. use traits::{Zero, One};
  8. use biguint::BigUint;
  9. use bigint::Sign;
  10. use bigint::Sign::{Minus, NoSign, Plus};
  11. #[allow(non_snake_case)]
  12. pub mod big_digit {
  13. /// A `BigDigit` is a `BigUint`'s composing element.
  14. pub type BigDigit = u32;
  15. /// A `DoubleBigDigit` is the internal type used to do the computations. Its
  16. /// size is the double of the size of `BigDigit`.
  17. pub type DoubleBigDigit = u64;
  18. pub const ZERO_BIG_DIGIT: BigDigit = 0;
  19. // `DoubleBigDigit` size dependent
  20. pub const BITS: usize = 32;
  21. pub const BASE: DoubleBigDigit = 1 << BITS;
  22. const LO_MASK: DoubleBigDigit = (-1i32 as DoubleBigDigit) >> BITS;
  23. #[inline]
  24. fn get_hi(n: DoubleBigDigit) -> BigDigit {
  25. (n >> BITS) as BigDigit
  26. }
  27. #[inline]
  28. fn get_lo(n: DoubleBigDigit) -> BigDigit {
  29. (n & LO_MASK) as BigDigit
  30. }
  31. /// Split one `DoubleBigDigit` into two `BigDigit`s.
  32. #[inline]
  33. pub fn from_doublebigdigit(n: DoubleBigDigit) -> (BigDigit, BigDigit) {
  34. (get_hi(n), get_lo(n))
  35. }
  36. /// Join two `BigDigit`s into one `DoubleBigDigit`
  37. #[inline]
  38. pub fn to_doublebigdigit(hi: BigDigit, lo: BigDigit) -> DoubleBigDigit {
  39. (lo as DoubleBigDigit) | ((hi as DoubleBigDigit) << BITS)
  40. }
  41. }
  42. use big_digit::{BigDigit, DoubleBigDigit};
  43. // Generic functions for add/subtract/multiply with carry/borrow:
  44. // Add with carry:
  45. #[inline]
  46. fn adc(a: BigDigit, b: BigDigit, carry: &mut BigDigit) -> BigDigit {
  47. let (hi, lo) = big_digit::from_doublebigdigit((a as DoubleBigDigit) + (b as DoubleBigDigit) +
  48. (*carry as DoubleBigDigit));
  49. *carry = hi;
  50. lo
  51. }
  52. // Subtract with borrow:
  53. #[inline]
  54. fn sbb(a: BigDigit, b: BigDigit, borrow: &mut BigDigit) -> BigDigit {
  55. let (hi, lo) = big_digit::from_doublebigdigit(big_digit::BASE + (a as DoubleBigDigit) -
  56. (b as DoubleBigDigit) -
  57. (*borrow as DoubleBigDigit));
  58. // hi * (base) + lo == 1*(base) + ai - bi - borrow
  59. // => ai - bi - borrow < 0 <=> hi == 0
  60. *borrow = (hi == 0) as BigDigit;
  61. lo
  62. }
  63. #[inline]
  64. pub fn mac_with_carry(a: BigDigit, b: BigDigit, c: BigDigit, carry: &mut BigDigit) -> BigDigit {
  65. let (hi, lo) = big_digit::from_doublebigdigit((a as DoubleBigDigit) +
  66. (b as DoubleBigDigit) * (c as DoubleBigDigit) +
  67. (*carry as DoubleBigDigit));
  68. *carry = hi;
  69. lo
  70. }
  71. /// Divide a two digit numerator by a one digit divisor, returns quotient and remainder:
  72. ///
  73. /// Note: the caller must ensure that both the quotient and remainder will fit into a single digit.
  74. /// This is _not_ true for an arbitrary numerator/denominator.
  75. ///
  76. /// (This function also matches what the x86 divide instruction does).
  77. #[inline]
  78. fn div_wide(hi: BigDigit, lo: BigDigit, divisor: BigDigit) -> (BigDigit, BigDigit) {
  79. debug_assert!(hi < divisor);
  80. let lhs = big_digit::to_doublebigdigit(hi, lo);
  81. let rhs = divisor as DoubleBigDigit;
  82. ((lhs / rhs) as BigDigit, (lhs % rhs) as BigDigit)
  83. }
  84. pub fn div_rem_digit(mut a: BigUint, b: BigDigit) -> (BigUint, BigDigit) {
  85. let mut rem = 0;
  86. for d in a.data.iter_mut().rev() {
  87. let (q, r) = div_wide(rem, *d, b);
  88. *d = q;
  89. rem = r;
  90. }
  91. (a.normalize(), rem)
  92. }
  93. // Only for the Add impl:
  94. #[must_use]
  95. #[inline]
  96. pub fn __add2(a: &mut [BigDigit], b: &[BigDigit]) -> BigDigit {
  97. debug_assert!(a.len() >= b.len());
  98. let mut carry = 0;
  99. let (a_lo, a_hi) = a.split_at_mut(b.len());
  100. for (a, b) in a_lo.iter_mut().zip(b) {
  101. *a = adc(*a, *b, &mut carry);
  102. }
  103. if carry != 0 {
  104. for a in a_hi {
  105. *a = adc(*a, 0, &mut carry);
  106. if carry == 0 { break }
  107. }
  108. }
  109. carry
  110. }
  111. /// /Two argument addition of raw slices:
  112. /// a += b
  113. ///
  114. /// The caller _must_ ensure that a is big enough to store the result - typically this means
  115. /// resizing a to max(a.len(), b.len()) + 1, to fit a possible carry.
  116. pub fn add2(a: &mut [BigDigit], b: &[BigDigit]) {
  117. let carry = __add2(a, b);
  118. debug_assert!(carry == 0);
  119. }
  120. pub fn sub2(a: &mut [BigDigit], b: &[BigDigit]) {
  121. let mut borrow = 0;
  122. let len = cmp::min(a.len(), b.len());
  123. let (a_lo, a_hi) = a.split_at_mut(len);
  124. let (b_lo, b_hi) = b.split_at(len);
  125. for (a, b) in a_lo.iter_mut().zip(b_lo) {
  126. *a = sbb(*a, *b, &mut borrow);
  127. }
  128. if borrow != 0 {
  129. for a in a_hi {
  130. *a = sbb(*a, 0, &mut borrow);
  131. if borrow == 0 { break }
  132. }
  133. }
  134. // note: we're _required_ to fail on underflow
  135. assert!(borrow == 0 && b_hi.iter().all(|x| *x == 0),
  136. "Cannot subtract b from a because b is larger than a.");
  137. }
  138. pub fn sub2rev(a: &[BigDigit], b: &mut [BigDigit]) {
  139. debug_assert!(b.len() >= a.len());
  140. let mut borrow = 0;
  141. let len = cmp::min(a.len(), b.len());
  142. let (a_lo, a_hi) = a.split_at(len);
  143. let (b_lo, b_hi) = b.split_at_mut(len);
  144. for (a, b) in a_lo.iter().zip(b_lo) {
  145. *b = sbb(*a, *b, &mut borrow);
  146. }
  147. assert!(a_hi.is_empty());
  148. // note: we're _required_ to fail on underflow
  149. assert!(borrow == 0 && b_hi.iter().all(|x| *x == 0),
  150. "Cannot subtract b from a because b is larger than a.");
  151. }
  152. pub fn sub_sign(a: &[BigDigit], b: &[BigDigit]) -> (Sign, BigUint) {
  153. // Normalize:
  154. let a = &a[..a.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)];
  155. let b = &b[..b.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)];
  156. match cmp_slice(a, b) {
  157. Greater => {
  158. let mut a = a.to_vec();
  159. sub2(&mut a, b);
  160. (Plus, BigUint::new(a))
  161. }
  162. Less => {
  163. let mut b = b.to_vec();
  164. sub2(&mut b, a);
  165. (Minus, BigUint::new(b))
  166. }
  167. _ => (NoSign, Zero::zero()),
  168. }
  169. }
  170. /// Three argument multiply accumulate:
  171. /// acc += b * c
  172. fn mac_digit(acc: &mut [BigDigit], b: &[BigDigit], c: BigDigit) {
  173. if c == 0 {
  174. return;
  175. }
  176. let mut b_iter = b.iter();
  177. let mut carry = 0;
  178. for ai in acc.iter_mut() {
  179. if let Some(bi) = b_iter.next() {
  180. *ai = mac_with_carry(*ai, *bi, c, &mut carry);
  181. } else if carry != 0 {
  182. *ai = mac_with_carry(*ai, 0, c, &mut carry);
  183. } else {
  184. break;
  185. }
  186. }
  187. assert!(carry == 0);
  188. }
  189. /// Three argument multiply accumulate:
  190. /// acc += b * c
  191. fn mac3(acc: &mut [BigDigit], b: &[BigDigit], c: &[BigDigit]) {
  192. let (x, y) = if b.len() < c.len() {
  193. (b, c)
  194. } else {
  195. (c, b)
  196. };
  197. // Karatsuba multiplication is slower than long multiplication for small x and y:
  198. //
  199. if x.len() <= 4 {
  200. for (i, xi) in x.iter().enumerate() {
  201. mac_digit(&mut acc[i..], y, *xi);
  202. }
  203. } else {
  204. /*
  205. * Karatsuba multiplication:
  206. *
  207. * The idea is that we break x and y up into two smaller numbers that each have about half
  208. * as many digits, like so (note that multiplying by b is just a shift):
  209. *
  210. * x = x0 + x1 * b
  211. * y = y0 + y1 * b
  212. *
  213. * With some algebra, we can compute x * y with three smaller products, where the inputs to
  214. * each of the smaller products have only about half as many digits as x and y:
  215. *
  216. * x * y = (x0 + x1 * b) * (y0 + y1 * b)
  217. *
  218. * x * y = x0 * y0
  219. * + x0 * y1 * b
  220. * + x1 * y0 * b
  221. * + x1 * y1 * b^2
  222. *
  223. * Let p0 = x0 * y0 and p2 = x1 * y1:
  224. *
  225. * x * y = p0
  226. * + (x0 * y1 + x1 * y0) * b
  227. * + p2 * b^2
  228. *
  229. * The real trick is that middle term:
  230. *
  231. * x0 * y1 + x1 * y0
  232. *
  233. * = x0 * y1 + x1 * y0 - p0 + p0 - p2 + p2
  234. *
  235. * = x0 * y1 + x1 * y0 - x0 * y0 - x1 * y1 + p0 + p2
  236. *
  237. * Now we complete the square:
  238. *
  239. * = -(x0 * y0 - x0 * y1 - x1 * y0 + x1 * y1) + p0 + p2
  240. *
  241. * = -((x1 - x0) * (y1 - y0)) + p0 + p2
  242. *
  243. * Let p1 = (x1 - x0) * (y1 - y0), and substitute back into our original formula:
  244. *
  245. * x * y = p0
  246. * + (p0 + p2 - p1) * b
  247. * + p2 * b^2
  248. *
  249. * Where the three intermediate products are:
  250. *
  251. * p0 = x0 * y0
  252. * p1 = (x1 - x0) * (y1 - y0)
  253. * p2 = x1 * y1
  254. *
  255. * In doing the computation, we take great care to avoid unnecessary temporary variables
  256. * (since creating a BigUint requires a heap allocation): thus, we rearrange the formula a
  257. * bit so we can use the same temporary variable for all the intermediate products:
  258. *
  259. * x * y = p2 * b^2 + p2 * b
  260. * + p0 * b + p0
  261. * - p1 * b
  262. *
  263. * The other trick we use is instead of doing explicit shifts, we slice acc at the
  264. * appropriate offset when doing the add.
  265. */
  266. /*
  267. * When x is smaller than y, it's significantly faster to pick b such that x is split in
  268. * half, not y:
  269. */
  270. let b = x.len() / 2;
  271. let (x0, x1) = x.split_at(b);
  272. let (y0, y1) = y.split_at(b);
  273. /*
  274. * We reuse the same BigUint for all the intermediate multiplies and have to size p
  275. * appropriately here: x1.len() >= x0.len and y1.len() >= y0.len():
  276. */
  277. let len = x1.len() + y1.len() + 1;
  278. let mut p = BigUint { data: vec![0; len] };
  279. // p2 = x1 * y1
  280. mac3(&mut p.data[..], x1, y1);
  281. // Not required, but the adds go faster if we drop any unneeded 0s from the end:
  282. p = p.normalize();
  283. add2(&mut acc[b..], &p.data[..]);
  284. add2(&mut acc[b * 2..], &p.data[..]);
  285. // Zero out p before the next multiply:
  286. p.data.truncate(0);
  287. p.data.extend(repeat(0).take(len));
  288. // p0 = x0 * y0
  289. mac3(&mut p.data[..], x0, y0);
  290. p = p.normalize();
  291. add2(&mut acc[..], &p.data[..]);
  292. add2(&mut acc[b..], &p.data[..]);
  293. // p1 = (x1 - x0) * (y1 - y0)
  294. // We do this one last, since it may be negative and acc can't ever be negative:
  295. let (j0_sign, j0) = sub_sign(x1, x0);
  296. let (j1_sign, j1) = sub_sign(y1, y0);
  297. match j0_sign * j1_sign {
  298. Plus => {
  299. p.data.truncate(0);
  300. p.data.extend(repeat(0).take(len));
  301. mac3(&mut p.data[..], &j0.data[..], &j1.data[..]);
  302. p = p.normalize();
  303. sub2(&mut acc[b..], &p.data[..]);
  304. },
  305. Minus => {
  306. mac3(&mut acc[b..], &j0.data[..], &j1.data[..]);
  307. },
  308. NoSign => (),
  309. }
  310. }
  311. }
  312. pub fn mul3(x: &[BigDigit], y: &[BigDigit]) -> BigUint {
  313. let len = x.len() + y.len() + 1;
  314. let mut prod = BigUint { data: vec![0; len] };
  315. mac3(&mut prod.data[..], x, y);
  316. prod.normalize()
  317. }
  318. pub fn div_rem(u: &BigUint, d: &BigUint) -> (BigUint, BigUint) {
  319. if d.is_zero() {
  320. panic!()
  321. }
  322. if u.is_zero() {
  323. return (Zero::zero(), Zero::zero());
  324. }
  325. if *d == One::one() {
  326. return (u.clone(), Zero::zero());
  327. }
  328. // Required or the q_len calculation below can underflow:
  329. match u.cmp(d) {
  330. Less => return (Zero::zero(), u.clone()),
  331. Equal => return (One::one(), Zero::zero()),
  332. Greater => {} // Do nothing
  333. }
  334. // This algorithm is from Knuth, TAOCP vol 2 section 4.3, algorithm D:
  335. //
  336. // First, normalize the arguments so the highest bit in the highest digit of the divisor is
  337. // set: the main loop uses the highest digit of the divisor for generating guesses, so we
  338. // want it to be the largest number we can efficiently divide by.
  339. //
  340. let shift = d.data.last().unwrap().leading_zeros() as usize;
  341. let mut a = u << shift;
  342. let b = d << shift;
  343. // The algorithm works by incrementally calculating "guesses", q0, for part of the
  344. // remainder. Once we have any number q0 such that q0 * b <= a, we can set
  345. //
  346. // q += q0
  347. // a -= q0 * b
  348. //
  349. // and then iterate until a < b. Then, (q, a) will be our desired quotient and remainder.
  350. //
  351. // q0, our guess, is calculated by dividing the last few digits of a by the last digit of b
  352. // - this should give us a guess that is "close" to the actual quotient, but is possibly
  353. // greater than the actual quotient. If q0 * b > a, we simply use iterated subtraction
  354. // until we have a guess such that q0 & b <= a.
  355. //
  356. let bn = *b.data.last().unwrap();
  357. let q_len = a.data.len() - b.data.len() + 1;
  358. let mut q = BigUint { data: vec![0; q_len] };
  359. // We reuse the same temporary to avoid hitting the allocator in our inner loop - this is
  360. // sized to hold a0 (in the common case; if a particular digit of the quotient is zero a0
  361. // can be bigger).
  362. //
  363. let mut tmp = BigUint { data: Vec::with_capacity(2) };
  364. for j in (0..q_len).rev() {
  365. /*
  366. * When calculating our next guess q0, we don't need to consider the digits below j
  367. * + b.data.len() - 1: we're guessing digit j of the quotient (i.e. q0 << j) from
  368. * digit bn of the divisor (i.e. bn << (b.data.len() - 1) - so the product of those
  369. * two numbers will be zero in all digits up to (j + b.data.len() - 1).
  370. */
  371. let offset = j + b.data.len() - 1;
  372. if offset >= a.data.len() {
  373. continue;
  374. }
  375. /* just avoiding a heap allocation: */
  376. let mut a0 = tmp;
  377. a0.data.truncate(0);
  378. a0.data.extend(a.data[offset..].iter().cloned());
  379. /*
  380. * q0 << j * big_digit::BITS is our actual quotient estimate - we do the shifts
  381. * implicitly at the end, when adding and subtracting to a and q. Not only do we
  382. * save the cost of the shifts, the rest of the arithmetic gets to work with
  383. * smaller numbers.
  384. */
  385. let (mut q0, _) = div_rem_digit(a0, bn);
  386. let mut prod = &b * &q0;
  387. while cmp_slice(&prod.data[..], &a.data[j..]) == Greater {
  388. let one: BigUint = One::one();
  389. q0 = q0 - one;
  390. prod = prod - &b;
  391. }
  392. add2(&mut q.data[j..], &q0.data[..]);
  393. sub2(&mut a.data[j..], &prod.data[..]);
  394. a = a.normalize();
  395. tmp = q0;
  396. }
  397. debug_assert!(a < b);
  398. (q.normalize(), a >> shift)
  399. }
  400. /// Find last set bit
  401. /// fls(0) == 0, fls(u32::MAX) == 32
  402. pub fn fls<T: traits::PrimInt>(v: T) -> usize {
  403. mem::size_of::<T>() * 8 - v.leading_zeros() as usize
  404. }
  405. pub fn ilog2<T: traits::PrimInt>(v: T) -> usize {
  406. fls(v) - 1
  407. }
  408. #[inline]
  409. pub fn biguint_shl(n: Cow<BigUint>, bits: usize) -> BigUint {
  410. let n_unit = bits / big_digit::BITS;
  411. let mut data = match n_unit {
  412. 0 => n.into_owned().data,
  413. _ => {
  414. let len = n_unit + n.data.len() + 1;
  415. let mut data = Vec::with_capacity(len);
  416. data.extend(repeat(0).take(n_unit));
  417. data.extend(n.data.iter().cloned());
  418. data
  419. }
  420. };
  421. let n_bits = bits % big_digit::BITS;
  422. if n_bits > 0 {
  423. let mut carry = 0;
  424. for elem in data[n_unit..].iter_mut() {
  425. let new_carry = *elem >> (big_digit::BITS - n_bits);
  426. *elem = (*elem << n_bits) | carry;
  427. carry = new_carry;
  428. }
  429. if carry != 0 {
  430. data.push(carry);
  431. }
  432. }
  433. BigUint::new(data)
  434. }
  435. #[inline]
  436. pub fn biguint_shr(n: Cow<BigUint>, bits: usize) -> BigUint {
  437. let n_unit = bits / big_digit::BITS;
  438. if n_unit >= n.data.len() {
  439. return Zero::zero();
  440. }
  441. let mut data = match n_unit {
  442. 0 => n.into_owned().data,
  443. _ => n.data[n_unit..].to_vec(),
  444. };
  445. let n_bits = bits % big_digit::BITS;
  446. if n_bits > 0 {
  447. let mut borrow = 0;
  448. for elem in data.iter_mut().rev() {
  449. let new_borrow = *elem << (big_digit::BITS - n_bits);
  450. *elem = (*elem >> n_bits) | borrow;
  451. borrow = new_borrow;
  452. }
  453. }
  454. BigUint::new(data)
  455. }
  456. pub fn cmp_slice(a: &[BigDigit], b: &[BigDigit]) -> Ordering {
  457. debug_assert!(a.last() != Some(&0));
  458. debug_assert!(b.last() != Some(&0));
  459. let (a_len, b_len) = (a.len(), b.len());
  460. if a_len < b_len {
  461. return Less;
  462. }
  463. if a_len > b_len {
  464. return Greater;
  465. }
  466. for (&ai, &bi) in a.iter().rev().zip(b.iter().rev()) {
  467. if ai < bi {
  468. return Less;
  469. }
  470. if ai > bi {
  471. return Greater;
  472. }
  473. }
  474. return Equal;
  475. }
  476. #[cfg(test)]
  477. mod algorithm_tests {
  478. use {BigDigit, BigUint, BigInt};
  479. use Sign::Plus;
  480. use traits::Num;
  481. #[test]
  482. fn test_sub_sign() {
  483. use super::sub_sign;
  484. fn sub_sign_i(a: &[BigDigit], b: &[BigDigit]) -> BigInt {
  485. let (sign, val) = sub_sign(a, b);
  486. BigInt::from_biguint(sign, val)
  487. }
  488. let a = BigUint::from_str_radix("265252859812191058636308480000000", 10).unwrap();
  489. let b = BigUint::from_str_radix("26525285981219105863630848000000", 10).unwrap();
  490. let a_i = BigInt::from_biguint(Plus, a.clone());
  491. let b_i = BigInt::from_biguint(Plus, b.clone());
  492. assert_eq!(sub_sign_i(&a.data[..], &b.data[..]), &a_i - &b_i);
  493. assert_eq!(sub_sign_i(&b.data[..], &a.data[..]), &b_i - &a_i);
  494. }
  495. }