polynomials/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
use core::num;
use std::ops::{Add, Mul};
fn modulo(a: i32, n: i32) -> i32 {
    ((a % n) + n) % n
}
fn mod_inverse(b: i64, p: i64) -> i64 {
    let mut a = b;
    let mut m = p;
    let mut u = 1;
    let mut v = 0;

    while a != 0 {
        let t = m / a;
        m -= t * a;
        std::mem::swap(&mut a, &mut m);
        v -= t * u;
        std::mem::swap(&mut u, &mut v);
    }

    (v + p) % p
}
/// Represents a single term in a polynomial, consisting of an exponent and a coefficient.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Monomial {
    /// The exponent of the monomial.
    pub exponent: u32,
    /// The coefficient of the monomial.
    pub coefficients: i64,
}
impl Monomial {
    /// Creates a new `Monomial` with the given exponent and coefficient.
    ///
    /// # Arguments
    ///
    /// * `exponent` - The exponent of the monomial.
    /// * `coefficients` - The coefficient of the monomial.
    ///
    /// # Returns
    ///
    /// A new `Monomial` instance.
    pub fn new(exponent: u32, coefficients: i64) -> Monomial {
        Monomial {
            exponent,
            coefficients,
        }
    }
    /// Creates a default `Monomial` with an exponent of 0 and a coefficient of 0.0.
    ///
    /// # Returns
    ///
    /// A default `Monomial` instance.
    pub fn default() -> Monomial {
        Monomial {
            exponent: 0,
            coefficients: 0,
        }
    }
}
/// Represents a polynomial, which is a sum of monomials.
#[derive(Debug, Clone)]
pub struct UnivariatePolynomial {
    /// The list of monomials that make up the polynomial.
    monomials: Vec<Monomial>,
    /// The degree of the polynomial, if known.
    pub degree: Option<u32>,
    pub prime_modulo: Option<u32>,
}
impl UnivariatePolynomial {
    /// Adds a monomial to the polynomial. If a monomial with the same exponent already exists,
    /// their coefficients are combined.
    ///
    /// # Arguments
    ///
    /// * `exponent` - The exponent of the monomial to add.
    /// * `coefficients` - The coefficient of the monomial to add.

    pub fn new(monomials: Vec<Monomial>, prime_modulo: u32) -> UnivariatePolynomial {
        UnivariatePolynomial {
            monomials,
            degree: None,
            prime_modulo: Some(prime_modulo),
        }
    }
    /// Creates a default `Polynomial` with no monomials and no degree.
    ///
    /// # Returns
    ///
    /// A default `Polynomial` instance.
    pub fn default() -> UnivariatePolynomial {
        UnivariatePolynomial {
            monomials: Vec::new(),
            degree: None,
            prime_modulo: Some(1),
        }
    }
    pub fn set_prime_modulo(&mut self, prime_modulo: u32) {
        self.prime_modulo = Some(prime_modulo);
    }
    /// Evaluates the polynomial at a given value of `x`.
    ///
    /// # Arguments
    ///
    /// * `x` - The value at which to evaluate the polynomial.
    ///
    /// # Returns
    ///
    /// The result of evaluating the polynomial at `x`.
    pub fn evaluate(&self, x: i64) -> i64 {
        let mut result: i64 = 0;
        let n = self.monomials.len();
        for i in 0..n {
            result += self.monomials[i].coefficients * x.pow(self.monomials[i].exponent as u32);
        }
        return result;
    }

    /// Returns the degree of the polynomial.
    ///
    /// # Returns
    ///
    /// The degree of the polynomial, if known.
    pub fn degree(&mut self) -> Option<u32> {
        let n = self.monomials.len();
        if self.degree.is_none() {
            for i in 0..n {
                if self.monomials[i].exponent > self.degree.unwrap_or(0) {
                    self.degree = Some(self.monomials[i].exponent);
                }
            }
            return self.degree;
        } else {
            return self.degree;
        }
    }
    /// Performs Lagrange interpolation to find a polynomial that passes through the given points.
    ///
    /// # Arguments
    ///
    /// * `x` - A vector of x-coordinates of the points.
    /// * `y` - A vector of y-coordinates of the points.
    ///
    /// # Returns
    ///
    /// A `UnivariatePolynomial` that passes through the given points.
    //add prime modulo
    pub fn interpolate(x: Vec<i64>, y: Vec<i64>, p: u32) -> UnivariatePolynomial {
        let n = x.len();
        let mut result = UnivariatePolynomial::default();

        result.set_prime_modulo(p);

        for i in 0..n {
            let mut denominator: i64 = 1;

            let mut numerator = UnivariatePolynomial::new(vec![Monomial::new(0, 1)], p);

            let mut a = y[i];
            for j in 0..n {
                if i != j {
                    let x_n = Monomial::new(1, 1); // x
                    let x_j =
                        Monomial::new(0, modulo((-x[j]).try_into().unwrap(), p as i32) as i64);
                    let temp_poly = UnivariatePolynomial::new(vec![x_n, x_j], p);

                    numerator = numerator * temp_poly;

                    denominator *= x[i] - x[j];
                    denominator = modulo(denominator as i32, p as i32) as i64;
                }
            }

            a = a * mod_inverse(denominator, p as i64);

            for monomial in &mut numerator.monomials {
                monomial.coefficients = modulo((monomial.coefficients * a) as i32, p as i32) as i64;
            }

            result = result + numerator;
        }

        result
    }
}

impl Mul for UnivariatePolynomial {
    type Output = UnivariatePolynomial;
    /// Multiplies two polynomials and returns the result.
    ///
    /// # Arguments
    ///
    /// * `p2` - The polynomial to multiply by.
    ///
    /// # Returns
    ///
    /// A new `Polynomial` representing the product of the two polynomials.

    fn mul(self, p2: UnivariatePolynomial) -> Self {
        let p1: Vec<Monomial> = self.monomials;
        let p2: Vec<Monomial> = p2.monomials;
        let p: u32 = self.prime_modulo.unwrap();

        let mut polynomial: Vec<Monomial> = Vec::new();
        for i in 0..p1.len() {
            for j in 0..p2.len() {
                let coefficients = modulo(
                    (modulo(p1[i].coefficients as i32, p as i32) as i64
                        * modulo(p2[j].coefficients as i32, p as i32) as i64)
                        as i32,
                    p as i32,
                ) as i64;
                polynomial.push(Monomial {
                    coefficients: (coefficients % p as i64 + p as i64) % p as i64,

                    exponent: p1[i].exponent.wrapping_add(p2[j].exponent),
                });
            }
        }
        // Combine monomials with the same exponent
        for i in 0..polynomial.len() {
            let mut j = i + 1;
            while j < polynomial.len() {
                if polynomial[i].exponent == polynomial[j].exponent {
                    polynomial[i].coefficients =
                        polynomial[i].coefficients + polynomial[j].coefficients;
                    polynomial[i].coefficients =
                        modulo((polynomial[i].coefficients) as i32, p as i32) as i64;

                    polynomial.remove(j);
                } else {
                    j += 1;
                }
            }
        }
        polynomial.sort();

        UnivariatePolynomial {
            monomials: polynomial,
            degree: None,
            prime_modulo: Some(p),
        }
    }
}

impl Add for UnivariatePolynomial {
    type Output = UnivariatePolynomial;
    /// Adds two polynomials and returns the result.
    ///
    /// # Arguments
    ///
    /// * `p2` - The polynomial to add.
    ///
    /// # Returns
    ///
    /// A new `Polynomial` representing the sum of the two polynomials.

    fn add(self, p2: UnivariatePolynomial) -> Self {
        let p1: Vec<Monomial> = self.monomials;
        let p2: Vec<Monomial> = p2.monomials;
        let mut polynomial: Vec<Monomial> = Vec::new();
        let p: u32 = self.prime_modulo.unwrap();
        polynomial = [p1, p2].concat();
        // Combine monomials with the same exponent

        for i in 0..polynomial.len() {
            let mut j = i + 1;
            while j < polynomial.len() {
                if polynomial[i].exponent == polynomial[j].exponent {
                    polynomial[i].coefficients =
                        polynomial[i].coefficients + polynomial[j].coefficients;
                    polynomial[i].coefficients =
                        modulo((polynomial[i].coefficients) as i32, p as i32) as i64;

                    polynomial.remove(j);
                } else {
                    j += 1;
                }
            }
        }
        polynomial.sort();
        UnivariatePolynomial {
            monomials: polynomial,
            degree: None,
            prime_modulo: Some(p),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    /// Tests the `evaluate` method of the `Polynomial` struct.
    fn test_evaluate() {
        let default = UnivariatePolynomial::default();
        let m1 = Monomial::new(2, 3);
        let m2 = Monomial::new(1, 2);
        let m3 = Monomial::new(0, 5);

        let p = UnivariatePolynomial {
            monomials: vec![m1, m2, m3],
            ..default
        };
        let result = p.evaluate(4);
        assert_eq!(result, 61);
    }

    /// Tests the `degree` method of the `UnivariatePolynomial` struct.

    #[test]
    fn test_degree() {
        let default = UnivariatePolynomial::default();
        let m1 = Monomial::new(2, 3);
        let m2 = Monomial::new(1, 2);

        let mut p = UnivariatePolynomial {
            monomials: vec![m1, m2],
            ..default
        };
        let result = p.degree();
        assert_eq!(result, Some(2));
    }

    /// Tests the multiplication of two UnivariatePolynomials.

    #[test]
    fn test_multiplication() {
        let default = UnivariatePolynomial::default();
        let m1 = Monomial::new(2, 5);
        let m2 = Monomial::new(1, -4);
        let m5 = Monomial::new(0, 2);
        let m3 = Monomial::new(3, 1);
        let m4 = Monomial::new(2, -2);
        let m6 = Monomial::new(0, 5);

        let p1 = UnivariatePolynomial {
            monomials: vec![m1, m2, m5],
            prime_modulo: Some(6),
            ..default
        };
        let p2 = UnivariatePolynomial {
            monomials: vec![m3, m4, m6],
            ..default
        };
        let result = p1 * p2;
        assert_eq!(result.monomials[5].coefficients, 5);
        assert_eq!(result.monomials[4].coefficients, 4);
        assert_eq!(result.monomials[3].coefficients, 4);
        assert_eq!(result.monomials[2].coefficients, 3);
        assert_eq!(result.monomials[1].coefficients, 4);
        assert_eq!(result.monomials[0].coefficients, 4);
        assert_eq!(result.monomials[5].exponent, 5);
        assert_eq!(result.monomials[4].exponent, 4);
        assert_eq!(result.monomials[3].exponent, 3);
        assert_eq!(result.monomials[2].exponent, 2);
        assert_eq!(result.monomials[1].exponent, 1);
        assert_eq!(result.monomials[0].exponent, 0);
    }

    /// Tests the Lagrange interpolation method.
    #[test]
    fn test_interpolate() {
        let x = vec![0, -2, 2];
        let y = vec![4, 1, 3];
        let p = 5;
        let result = UnivariatePolynomial::interpolate(x, y, p);
        assert_eq!(result.monomials[0].coefficients, 4);
        assert_eq!(result.monomials[0].exponent, 0);
        assert_eq!(result.monomials[1].coefficients, 3);
        assert_eq!(result.monomials[1].exponent, 1);
        assert_eq!(result.monomials[2].coefficients, 2);
        assert_eq!(result.monomials[2].exponent, 2);
    }
}