1use super::addition::{__add2, add2};
2use super::subtraction::sub2;
3use super::{biguint_from_vec, cmp_slice, BigUint, IntDigits};
4
5use crate::big_digit::{self, BigDigit, BigDigits, DoubleBigDigit};
6use crate::Sign::{self, Minus, NoSign, Plus};
7use crate::{BigInt, UsizePromotion};
8
9use core::cmp::Ordering;
10use core::iter::Product;
11use core::ops::{Mul, MulAssign};
12use num_traits::{CheckedMul, FromPrimitive, Zero};
13
14#[inline]
15pub(super) fn mac_with_carry(
16 a: BigDigit,
17 b: BigDigit,
18 c: BigDigit,
19 acc: &mut DoubleBigDigit,
20) -> BigDigit {
21 *acc += DoubleBigDigit::from(a);
22 *acc += DoubleBigDigit::from(b) * DoubleBigDigit::from(c);
23 let lo = *acc as BigDigit;
24 *acc >>= big_digit::BITS;
25 lo
26}
27
28#[inline]
29fn mul_with_carry(a: BigDigit, b: BigDigit, acc: &mut DoubleBigDigit) -> BigDigit {
30 *acc += DoubleBigDigit::from(a) * DoubleBigDigit::from(b);
31 let lo = *acc as BigDigit;
32 *acc >>= big_digit::BITS;
33 lo
34}
35
36fn mac_digit(acc: &mut [BigDigit], b: &[BigDigit], c: BigDigit) {
39 if c == 0 {
40 return;
41 }
42
43 let mut carry = 0;
44 let (a_lo, a_hi) = acc.split_at_mut(b.len());
45
46 for (a, &b) in a_lo.iter_mut().zip(b) {
47 *a = mac_with_carry(*a, b, c, &mut carry);
48 }
49
50 let (carry_hi, carry_lo) = big_digit::from_doublebigdigit(carry);
51 if true {
{
match (&carry_hi, &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("mac_with_carry never keeps high bits")));
}
}
}
};
};debug_assert_eq!(carry_hi, 0, "mac_with_carry never keeps high bits");
52
53 let final_carry = __add2(a_hi, &[carry_lo]);
54 {
match (&final_carry, &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("carry overflow during multiplication!")));
}
}
}
};assert_eq!(final_carry, 0, "carry overflow during multiplication!");
55}
56
57fn bigint_from_slice(slice: &[BigDigit]) -> BigInt {
58 let mut u = BigUint {
59 data: BigDigits::from_slice(slice),
60 };
61 u.normalize();
62 BigInt::from(u)
63}
64
65#[allow(clippy::many_single_char_names)]
68fn mac3(mut acc: &mut [BigDigit], mut b: &[BigDigit], mut c: &[BigDigit]) {
69 if let Some(&0) = b.first() {
71 if let Some(nz) = b.iter().position(|&d| d != 0) {
72 b = &b[nz..];
73 acc = &mut acc[nz..];
74 } else {
75 return;
76 }
77 }
78 if let Some(&0) = c.first() {
79 if let Some(nz) = c.iter().position(|&d| d != 0) {
80 c = &c[nz..];
81 acc = &mut acc[nz..];
82 } else {
83 return;
84 }
85 }
86
87 let acc = acc;
88 let (x, y) = if b.len() < c.len() { (b, c) } else { (c, b) };
89
90 if x.len() <= 32 {
103 for (i, xi) in x.iter().enumerate() {
105 mac_digit(&mut acc[i..], y, *xi);
106 }
107 } else if x.len() * 2 <= y.len() {
108 let m2 = y.len() / 2;
161 let (low2, high2) = y.split_at(m2);
162
163 mac3(acc, x, low2);
165 mac3(&mut acc[m2..], x, high2);
166 } else if x.len() <= 256 {
167 let b = x.len() / 2;
231 let (x0, x1) = x.split_at(b);
232 let (y0, y1) = y.split_at(b);
233
234 let len = x1.len() + y1.len() + 1;
237 let mut p = BigUint {
238 data: BigDigits::from_vec(::alloc::vec::from_elem(0, len)vec![0; len]),
239 };
240
241 mac3(&mut p.data, x1, y1);
243
244 p.normalize();
246
247 add2(&mut acc[b..], &p.data);
248 add2(&mut acc[b * 2..], &p.data);
249
250 p.data.clear();
252 p.data.resize(len, 0);
253
254 mac3(&mut p.data, x0, y0);
256 p.normalize();
257
258 add2(acc, &p.data);
259 add2(&mut acc[b..], &p.data);
260
261 let (j0_sign, j0) = sub_sign(x1, x0);
264 let (j1_sign, j1) = sub_sign(y1, y0);
265
266 match j0_sign * j1_sign {
267 Plus => {
268 p.data.clear();
269 p.data.resize(len, 0);
270
271 mac3(&mut p.data, &j0.data, &j1.data);
272 p.normalize();
273
274 sub2(&mut acc[b..], &p.data);
275 }
276 Minus => {
277 mac3(&mut acc[b..], &j0.data, &j1.data);
278 }
279 NoSign => (),
280 }
281 } else {
282 let i = y.len() / 3 + 1;
291
292 let x0_len = Ord::min(x.len(), i);
293 let x1_len = Ord::min(x.len() - x0_len, i);
294
295 let y0_len = i;
296 let y1_len = Ord::min(y.len() - y0_len, i);
297
298 let x0 = bigint_from_slice(&x[..x0_len]);
304 let x1 = bigint_from_slice(&x[x0_len..x0_len + x1_len]);
305 let x2 = bigint_from_slice(&x[x0_len + x1_len..]);
306
307 let y0 = bigint_from_slice(&y[..y0_len]);
309 let y1 = bigint_from_slice(&y[y0_len..y0_len + y1_len]);
310 let y2 = bigint_from_slice(&y[y0_len + y1_len..]);
311
312 let p = &x0 + &x2;
338
339 let q = &y0 + &y2;
341
342 let p2 = &p - &x1;
344
345 let q2 = &q - &y1;
347
348 let r0 = &x0 * &y0;
350
351 let r4 = &x2 * &y2;
353
354 let r1 = (p + x1) * (q + y1);
356
357 let r2 = &p2 * &q2;
359
360 let r3 = ((p2 + x2) * 2 - x0) * ((q2 + y2) * 2 - y0);
362
363 let mut comp3: BigInt = (r3 - &r1) / 3u32;
383 let mut comp1: BigInt = (r1 - &r2) >> 1;
384 let mut comp2: BigInt = r2 - &r0;
385 comp3 = ((&comp2 - comp3) >> 1) + (&r4 << 1);
386 comp2 += &comp1 - &r4;
387 comp1 -= &comp3;
388
389 for (j, result) in [&r0, &comp1, &comp2, &comp3, &r4].iter().enumerate().rev() {
404 match result.sign() {
405 Plus => add2(&mut acc[i * j..], result.digits()),
406 Minus => sub2(&mut acc[i * j..], result.digits()),
407 NoSign => {}
408 }
409 }
410 }
411}
412
413fn mul3(x: &[BigDigit], y: &[BigDigit]) -> BigUint {
414 let len = x.len() + y.len() + 1;
415 let mut prod = BigUint {
416 data: BigDigits::from_vec(::alloc::vec::from_elem(0, len)vec![0; len]),
417 };
418
419 mac3(&mut prod.data, x, y);
420 prod.normalize();
421 prod
422}
423
424fn scalar_mul(a: &mut BigUint, b: BigDigit) {
425 match b {
426 0 => a.set_zero(),
427 1 => {}
428 _ => {
429 if b.is_power_of_two() {
430 *a <<= b.trailing_zeros();
431 } else {
432 let mut carry = 0;
433 for a in a.data.iter_mut() {
434 *a = mul_with_carry(*a, b, &mut carry);
435 }
436 if carry != 0 {
437 a.data.push(carry as BigDigit);
438 }
439 }
440 }
441 }
442}
443
444fn sub_sign(mut a: &[BigDigit], mut b: &[BigDigit]) -> (Sign, BigUint) {
445 if let Some(&0) = a.last() {
447 a = &a[..a.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)];
448 }
449 if let Some(&0) = b.last() {
450 b = &b[..b.iter().rposition(|&x| x != 0).map_or(0, |i| i + 1)];
451 }
452
453 match cmp_slice(a, b) {
454 Ordering::Greater => {
455 let mut a = a.to_vec();
456 sub2(&mut a, b);
457 (Plus, biguint_from_vec(a))
458 }
459 Ordering::Less => {
460 let mut b = b.to_vec();
461 sub2(&mut b, a);
462 (Minus, biguint_from_vec(b))
463 }
464 Ordering::Equal => (NoSign, BigUint::ZERO),
465 }
466}
467
468macro_rules! impl_mul {
469 ($(impl Mul<$Other:ty> for $Self:ty;)*) => {$(
470 impl Mul<$Other> for $Self {
471 type Output = BigUint;
472
473 #[inline]
474 fn mul(self, other: $Other) -> BigUint {
475 match (&*self.data, &*other.data) {
476 (&[], _) | (_, &[]) => BigUint::ZERO,
478 (_, &[digit]) => self * digit,
480 (&[digit], _) => other * digit,
481 (x, y) => mul3(x, y),
483 }
484 }
485 }
486 )*}
487}
488impl Mul<&BigUint> for &BigUint {
type Output = BigUint;
#[inline]
fn mul(self, other: &BigUint) -> BigUint {
match (&*self.data, &*other.data) {
(&[], _) | (_, &[]) => BigUint::ZERO,
(_, &[digit]) => self * digit,
(&[digit], _) => other * digit,
(x, y) => mul3(x, y),
}
}
}impl_mul! {
489 impl Mul<BigUint> for BigUint;
490 impl Mul<BigUint> for &BigUint;
491 impl Mul<&BigUint> for BigUint;
492 impl Mul<&BigUint> for &BigUint;
493}
494
495macro_rules! impl_mul_assign {
496 ($(impl MulAssign<$Other:ty> for BigUint;)*) => {$(
497 impl MulAssign<$Other> for BigUint {
498 #[inline]
499 fn mul_assign(&mut self, other: $Other) {
500 match (&*self.data, &*other.data) {
501 (&[], _) => {},
503 (_, &[]) => self.set_zero(),
504 (_, &[digit]) => *self *= digit,
506 (&[digit], _) => *self = other * digit,
507 (x, y) => *self = mul3(x, y),
509 }
510 }
511 }
512 )*}
513}
514impl MulAssign<&BigUint> for BigUint {
#[inline]
fn mul_assign(&mut self, other: &BigUint) {
match (&*self.data, &*other.data) {
(&[], _) => {}
(_, &[]) => self.set_zero(),
(_, &[digit]) => *self *= digit,
(&[digit], _) => *self = other * digit,
(x, y) => *self = mul3(x, y),
}
}
}impl_mul_assign! {
515 impl MulAssign<BigUint> for BigUint;
516 impl MulAssign<&BigUint> for BigUint;
517}
518
519impl Mul<&usize> for BigUint {
type Output = BigUint;
#[inline]
fn mul(self, other: &usize) -> BigUint { Mul::mul(self, *other) }
}
impl Mul<BigUint> for &usize {
type Output = BigUint;
#[inline]
fn mul(self, other: BigUint) -> BigUint { Mul::mul(*self, other) }
}
impl Mul<usize> for &BigUint {
type Output = BigUint;
#[inline]
fn mul(self, other: usize) -> BigUint { Mul::mul(self.clone(), other) }
}
impl Mul<&BigUint> for usize {
type Output = BigUint;
#[inline]
fn mul(self, other: &BigUint) -> BigUint { Mul::mul(self, other.clone()) }
}
impl Mul<&usize> for &BigUint {
type Output = BigUint;
#[inline]
fn mul(self, other: &usize) -> BigUint { Mul::mul(self.clone(), *other) }
}
impl Mul<&BigUint> for &usize {
type Output = BigUint;
#[inline]
fn mul(self, other: &BigUint) -> BigUint {
Mul::mul(*self, other.clone())
}
}
impl Mul<usize> for BigUint {
type Output = BigUint;
#[allow(clippy :: cast_lossless)]
#[inline]
fn mul(self, other: usize) -> BigUint {
Mul::mul(self, other as UsizePromotion)
}
}
impl Mul<BigUint> for usize {
type Output = BigUint;
#[allow(clippy :: cast_lossless)]
#[inline]
fn mul(self, other: BigUint) -> BigUint {
Mul::mul(self as UsizePromotion, other)
}
}promote_unsigned_scalars!(impl Mul for BigUint, mul);
520impl MulAssign<usize> for BigUint {
#[allow(clippy :: cast_lossless)]
#[inline]
fn mul_assign(&mut self, other: usize) {
self.mul_assign(other as UsizePromotion);
}
}promote_unsigned_scalars_assign!(impl MulAssign for BigUint, mul_assign);
521impl Mul<BigUint> for u32 {
type Output = BigUint;
#[inline]
fn mul(self, other: BigUint) -> BigUint { Mul::mul(other, self) }
}
impl Mul<&u32> for BigUint {
type Output = BigUint;
#[inline]
fn mul(self, other: &u32) -> BigUint { Mul::mul(self, *other) }
}
impl Mul<BigUint> for &u32 {
type Output = BigUint;
#[inline]
fn mul(self, other: BigUint) -> BigUint { Mul::mul(*self, other) }
}
impl Mul<u32> for &BigUint {
type Output = BigUint;
#[inline]
fn mul(self, other: u32) -> BigUint { Mul::mul(self.clone(), other) }
}
impl Mul<&BigUint> for u32 {
type Output = BigUint;
#[inline]
fn mul(self, other: &BigUint) -> BigUint { Mul::mul(self, other.clone()) }
}
impl Mul<&u32> for &BigUint {
type Output = BigUint;
#[inline]
fn mul(self, other: &u32) -> BigUint { Mul::mul(self.clone(), *other) }
}
impl Mul<&BigUint> for &u32 {
type Output = BigUint;
#[inline]
fn mul(self, other: &BigUint) -> BigUint {
Mul::mul(*self, other.clone())
}
}forward_all_scalar_binop_to_val_val_commutative!(impl Mul<u32> for BigUint, mul);
522impl Mul<BigUint> for u64 {
type Output = BigUint;
#[inline]
fn mul(self, other: BigUint) -> BigUint { Mul::mul(other, self) }
}
impl Mul<&u64> for BigUint {
type Output = BigUint;
#[inline]
fn mul(self, other: &u64) -> BigUint { Mul::mul(self, *other) }
}
impl Mul<BigUint> for &u64 {
type Output = BigUint;
#[inline]
fn mul(self, other: BigUint) -> BigUint { Mul::mul(*self, other) }
}
impl Mul<u64> for &BigUint {
type Output = BigUint;
#[inline]
fn mul(self, other: u64) -> BigUint { Mul::mul(self.clone(), other) }
}
impl Mul<&BigUint> for u64 {
type Output = BigUint;
#[inline]
fn mul(self, other: &BigUint) -> BigUint { Mul::mul(self, other.clone()) }
}
impl Mul<&u64> for &BigUint {
type Output = BigUint;
#[inline]
fn mul(self, other: &u64) -> BigUint { Mul::mul(self.clone(), *other) }
}
impl Mul<&BigUint> for &u64 {
type Output = BigUint;
#[inline]
fn mul(self, other: &BigUint) -> BigUint {
Mul::mul(*self, other.clone())
}
}forward_all_scalar_binop_to_val_val_commutative!(impl Mul<u64> for BigUint, mul);
523impl Mul<BigUint> for u128 {
type Output = BigUint;
#[inline]
fn mul(self, other: BigUint) -> BigUint { Mul::mul(other, self) }
}
impl Mul<&u128> for BigUint {
type Output = BigUint;
#[inline]
fn mul(self, other: &u128) -> BigUint { Mul::mul(self, *other) }
}
impl Mul<BigUint> for &u128 {
type Output = BigUint;
#[inline]
fn mul(self, other: BigUint) -> BigUint { Mul::mul(*self, other) }
}
impl Mul<u128> for &BigUint {
type Output = BigUint;
#[inline]
fn mul(self, other: u128) -> BigUint { Mul::mul(self.clone(), other) }
}
impl Mul<&BigUint> for u128 {
type Output = BigUint;
#[inline]
fn mul(self, other: &BigUint) -> BigUint { Mul::mul(self, other.clone()) }
}
impl Mul<&u128> for &BigUint {
type Output = BigUint;
#[inline]
fn mul(self, other: &u128) -> BigUint { Mul::mul(self.clone(), *other) }
}
impl Mul<&BigUint> for &u128 {
type Output = BigUint;
#[inline]
fn mul(self, other: &BigUint) -> BigUint {
Mul::mul(*self, other.clone())
}
}forward_all_scalar_binop_to_val_val_commutative!(impl Mul<u128> for BigUint, mul);
524
525impl Mul<u32> for BigUint {
526 type Output = BigUint;
527
528 #[inline]
529 fn mul(mut self, other: u32) -> BigUint {
530 self *= other;
531 self
532 }
533}
534impl MulAssign<u32> for BigUint {
535 #[inline]
536 fn mul_assign(&mut self, other: u32) {
537 scalar_mul(self, other as BigDigit);
538 }
539}
540
541impl Mul<u64> for BigUint {
542 type Output = BigUint;
543
544 #[inline]
545 fn mul(mut self, other: u64) -> BigUint {
546 self *= other;
547 self
548 }
549}
550impl MulAssign<u64> for BigUint {
551 cfg_digit!(
552 #[inline]
553 fn mul_assign(&mut self, other: u64) {
554 if let Some(other) = BigDigit::from_u64(other) {
555 scalar_mul(self, other);
556 } else {
557 let (hi, lo) = big_digit::from_doublebigdigit(other);
558 *self = mul3(&self.data, &[lo, hi]);
559 }
560 }
561
562 #[inline]
563 fn mul_assign(&mut self, other: u64) {
564 scalar_mul(self, other);
565 }
566 );
567}
568
569impl Mul<u128> for BigUint {
570 type Output = BigUint;
571
572 #[inline]
573 fn mul(mut self, other: u128) -> BigUint {
574 self *= other;
575 self
576 }
577}
578
579impl MulAssign<u128> for BigUint {
580 cfg_digit!(
581 #[inline]
582 fn mul_assign(&mut self, other: u128) {
583 if let Some(other) = BigDigit::from_u128(other) {
584 scalar_mul(self, other);
585 } else {
586 *self = match super::u32_from_u128(other) {
587 (0, 0, c, d) => mul3(&self.data, &[d, c]),
588 (0, b, c, d) => mul3(&self.data, &[d, c, b]),
589 (a, b, c, d) => mul3(&self.data, &[d, c, b, a]),
590 };
591 }
592 }
593
594 #[inline]
595 fn mul_assign(&mut self, other: u128) {
596 if let Some(other) = BigDigit::from_u128(other) {
597 scalar_mul(self, other);
598 } else {
599 let (hi, lo) = big_digit::from_doublebigdigit(other);
600 *self = mul3(&self.data, &[lo, hi]);
601 }
602 }
603 );
604}
605
606impl CheckedMul for BigUint {
607 #[inline]
608 fn checked_mul(&self, v: &BigUint) -> Option<BigUint> {
609 Some(self.mul(v))
610 }
611}
612
613impl<T> Product<T> for BigUint where BigUint: Mul<T, Output = BigUint> {
fn product<I>(iter: I) -> Self where I: Iterator<Item = T> {
iter.fold(Self::ONE, <BigUint>::mul)
}
}impl_product_iter_type!(BigUint);
614
615#[test]
616fn test_sub_sign() {
617 use crate::BigInt;
618 use num_traits::Num;
619
620 fn sub_sign_i(a: &[BigDigit], b: &[BigDigit]) -> BigInt {
621 let (sign, val) = sub_sign(a, b);
622 BigInt::from_biguint(sign, val)
623 }
624
625 let a = BigUint::from_str_radix("265252859812191058636308480000000", 10).unwrap();
626 let b = BigUint::from_str_radix("26525285981219105863630848000000", 10).unwrap();
627 let a_i = BigInt::from(a.clone());
628 let b_i = BigInt::from(b.clone());
629
630 assert_eq!(sub_sign_i(&a.data, &b.data), &a_i - &b_i);
631 assert_eq!(sub_sign_i(&b.data, &a.data), &b_i - &a_i);
632}