malachite_base/num/arithmetic/mod_add_mul.rs
1// Copyright © 2026 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::num::arithmetic::traits::{ModAddMul, ModAddMulAssign};
10use crate::num::basic::unsigneds::PrimitiveUnsigned;
11
12fn assert_reduced<T: PrimitiveUnsigned>(x: T, y: T, z: T, m: T) {
13 assert!(x < m, "x must be reduced mod m, but {x} >= {m}");
14 assert!(y < m, "y must be reduced mod m, but {y} >= {m}");
15 assert!(z < m, "z must be reduced mod m, but {z} >= {m}");
16}
17
18#[inline]
19fn mod_add_mul<T: PrimitiveUnsigned>(x: T, y: T, z: T, m: T) -> T {
20 assert_reduced(x, y, z, m);
21 x.mod_add(y.mod_mul(z, m), m)
22}
23
24#[inline]
25fn mod_add_mul_assign<T: PrimitiveUnsigned>(x: &mut T, y: T, z: T, m: T) {
26 assert_reduced(*x, y, z, m);
27 x.mod_add_assign(y.mod_mul(z, m), m);
28}
29
30macro_rules! impl_mod_add_mul {
31 ($t:ident) => {
32 impl ModAddMul<$t> for $t {
33 type Output = $t;
34
35 /// Adds a number and the product of two other numbers, modulo a fourth number $m$. All
36 /// three inputs must be already reduced modulo $m$.
37 ///
38 /// $f(x, y, z, m) = w$, where $x, y, z, w < m$ and $x + yz \equiv w \mod m$.
39 ///
40 /// # Worst-case complexity
41 /// Constant time and additional memory.
42 ///
43 /// # Panics
44 /// Panics if `self`, `y`, or `z` are greater than or equal to `m`.
45 ///
46 /// # Examples
47 /// See [here](super::mod_add_mul#mod_add_mul).
48 #[inline]
49 fn mod_add_mul(self, y: $t, z: $t, m: $t) -> $t {
50 mod_add_mul(self, y, z, m)
51 }
52 }
53
54 impl ModAddMulAssign<$t> for $t {
55 /// Adds the product of two numbers to a third number, modulo a fourth number $m$, in
56 /// place. All three inputs must be already reduced modulo $m$.
57 ///
58 /// $x \gets w$, where $x, y, z, w < m$ and $x + yz \equiv w \mod m$.
59 ///
60 /// # Worst-case complexity
61 /// Constant time and additional memory.
62 ///
63 /// # Panics
64 /// Panics if `self`, `y`, or `z` are greater than or equal to `m`.
65 ///
66 /// # Examples
67 /// See [here](super::mod_add_mul#mod_add_mul_assign).
68 #[inline]
69 fn mod_add_mul_assign(&mut self, y: $t, z: $t, m: $t) {
70 mod_add_mul_assign(self, y, z, m);
71 }
72 }
73 };
74}
75apply_to_unsigneds!(impl_mod_add_mul);