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
use std::ops::{Add, Index, Mul, Neg, Sub};

use crate::math::polynomial::Polynomial;

impl Add<Polynomial> for Polynomial {
    type Output = Polynomial;

    fn add(self, rhs: Polynomial) -> Self::Output {
        let new_len = self.coefficients.len().max(rhs.coefficients.len());
        let mut coefficients = vec![0; new_len];
        let mut c1 = self.coefficients.iter().rev();
        let mut c2 = rhs.coefficients.iter().rev();
        for c in coefficients.iter_mut().rev() {
            *c = *c1.next().unwrap_or(&0) + *c2.next().unwrap_or(&0);
        }
        Polynomial::new(&coefficients)
    }
}

impl Sub<Polynomial> for Polynomial {
    type Output = Polynomial;

    fn sub(self, rhs: Polynomial) -> Self::Output {
        self.add(rhs.neg())
    }
}

impl Neg for Polynomial {
    type Output = Polynomial;

    fn neg(self) -> Self::Output {
        let coefficients: Vec<i64> = self.coefficients.iter().map(|&c| -c).collect();
        Polynomial::new(&coefficients)
    }
}

impl Add<i64> for Polynomial {
    type Output = Polynomial;

    fn add(self, rhs: i64) -> Self::Output {
        let mut p = self;
        *p.coefficients.last_mut().unwrap() += rhs;
        p
    }
}

impl Sub<i64> for Polynomial {
    type Output = Polynomial;

    fn sub(self, rhs: i64) -> Self::Output {
        self + (-rhs)
    }
}

impl Mul<i64> for Polynomial {
    type Output = Polynomial;

    fn mul(self, rhs: i64) -> Self::Output {
        let mut p = self;
        for c in &mut p.coefficients {
            *c *= rhs;
        }
        p
    }
}

impl Index<usize> for Polynomial {
    type Output = i64;

    fn index(&self, index: usize) -> &Self::Output {
        &self.coefficients[index]
    }
}