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
//! An integral exponential polynomial is a polynomial in form of
//! c<sub>1</sub>·b<sub>1</sub><sup>x</sup> +
//! c<sub>2</sub>·b<sub>1</sub><sup>x</sup> + ... +
//! c<sub>n</sub>·b<sub>n</sub><sup>x</sup>
//! where c<sub>1</sub>, c<sub>2</sub>, ..., c<sub>n</sub> are integers
//! and b<sub>1</sub>, b<sub>2</sub>, ..., b<sub>n</sub> are positive
//! integers, and the variable x can be any natural number.

extern crate num_bigint;
extern crate num_traits;

use num_bigint::{BigUint, BigInt};
use num_traits::{Zero, One, Signed, pow};
use std::{ops, fmt};

#[derive(Eq, PartialEq, Clone, Debug)]
struct Term {
    coeff: BigInt,
    base: BigUint,
}

#[derive(Eq, PartialEq, Clone, Debug)]
pub struct Polynomial {
    terms: Vec<Term>
}

impl Polynomial {
    /// Returns a new polynomial with at most one term. When either
    /// coefficient or base is zero, an empty polynomial is returned.
    ///
    /// # Arguments
    ///
    /// * `coeff` - A `BigInt` represents the coefficient of the term
    /// * `base` - A `BigUint` represents the base of the component
    ///            function
    /// ```
    pub fn one_term(coeff: BigInt, base: BigUint) -> Polynomial {
        Polynomial {
            terms: if base.is_zero() || coeff.is_zero() {
                vec![]
            } else {
                vec![Term { coeff: coeff, base: base }]
            }
        }
    }

    /// Returns the result for applying the given value to the
    /// polynomial.
    ///
    /// # Arguments
    ///
    /// * `value` - The value to be applied to the polynomial
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate integral_exponential_polynomial;
    /// # extern crate num_bigint;
    /// # extern crate num_traits;
    /// # use integral_exponential_polynomial::Polynomial;
    /// # use num_bigint::{BigInt, BigUint};
    /// # use num_traits::{pow};
    /// # fn main() {
    /// let p = Polynomial::one_term(BigInt::from(10), BigUint::from(20u8));
    /// assert_eq!(p.apply(30), (BigInt::from(10) *
    ///                          BigInt::from(pow(BigUint::from(20u8), 30))));
    /// # }
    /// ```
    pub fn apply(&self, value: usize) -> BigInt {
        self.terms.iter().fold(BigInt::zero(), |result, term| {
            let term = term.clone();
            result + term.coeff * BigInt::from(pow(term.base, value))
        })
    }
}

trait MergeOps {
    fn unary_op(rhs: BigInt) -> BigInt;
    fn binary_op(lhs: BigInt, rhs: BigInt) -> BigInt;
}

struct AddOps;
impl MergeOps for AddOps {
    fn unary_op(rhs: BigInt) -> BigInt {
        rhs
    }
    fn binary_op(lhs: BigInt, rhs: BigInt) -> BigInt {
        lhs + rhs
    }
}

struct SubOps;
impl MergeOps for SubOps {
    fn unary_op(rhs: BigInt) -> BigInt {
        -rhs
    }
    fn binary_op(lhs: BigInt, rhs: BigInt) -> BigInt {
        lhs - rhs
    }
}


fn merge_terms<Ops: MergeOps>(output: &mut Vec<Term>, _ops: Ops,
                              lhs: Vec<Term>, rhs: Vec<Term>) {
    assert!(output.is_empty());
    output.reserve(lhs.len() + rhs.len());
    let mut iter_lhs = lhs.into_iter();
    let mut iter_rhs = rhs.into_iter();
    let mut cur_lhs = iter_lhs.next();
    let mut cur_rhs = iter_rhs.next();

    loop {
        let (next_lhs, next_rhs, next_result) =
            match (cur_lhs, cur_rhs) {
                (Some(a), Some(b)) => {
                    if a.base < b.base {
                        (iter_lhs.next(), Some(b), a)
                    } else if a.base > b.base {
                        (Some(a), iter_rhs.next(), Term {
                            coeff: Ops::unary_op(b.coeff),
                            base: b.base
                        })
                    } else {
                        (iter_lhs.next(), iter_rhs.next(), Term {
                            coeff: Ops::binary_op(a.coeff, b.coeff),
                            base: a.base
                        })
                    }
                }
                (Some(a), None) => {
                    (iter_lhs.next(), None, a)
                }
                (None, Some(b)) => {
                    (None, iter_rhs.next(), Term {
                        coeff: Ops::unary_op(b.coeff),
                        base: b.base
                    })
                }
                (None, None) => {
                    break;
                }
            };
        if !next_result.coeff.is_zero() {
            output.push(next_result);
        }
        cur_lhs = next_lhs;
        cur_rhs = next_rhs;
    }

    output.shrink_to_fit();
}

impl ops::Add for Polynomial {
    type Output = Polynomial;
    fn add(self, other: Polynomial) -> Polynomial {
        let mut terms = vec![];
        merge_terms(&mut terms, AddOps, self.terms, other.terms);
        Polynomial { terms: terms }
    }
}

impl ops::Sub for Polynomial {
    type Output = Polynomial;
    fn sub(self, other: Polynomial) -> Polynomial {
        let mut terms = vec![];
        merge_terms(&mut terms, SubOps, self.terms, other.terms);
        Polynomial { terms: terms }
    }
}

impl ops::AddAssign for Polynomial {
    fn add_assign(&mut self, other: Polynomial) {
        let old_terms = self.terms.drain(..).collect();
        merge_terms(&mut self.terms, AddOps, old_terms, other.terms);
    }
}

impl ops::SubAssign for Polynomial {
    fn sub_assign(&mut self, other: Polynomial) {
        let old_terms = self.terms.drain(..).collect();
        merge_terms(&mut self.terms, SubOps, old_terms, other.terms);
    }
}

impl fmt::Display for Polynomial {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        let mut iter = self.terms.iter().rev();
        if let Some(first_term) = iter.next() {
            try!(if first_term.coeff == BigInt::one() {
                write!(fmt, "{}^x", first_term.base)
            } else {
                write!(fmt, "{}*{}^x", first_term.coeff, first_term.base)
            });
            for term in iter {
                let sign = if term.coeff.is_positive() { "+" } else { "-" };
                let abs_coeff = term.coeff.abs();
                try!(if abs_coeff == BigInt::one() {
                    write!(fmt, " {} {}^x", sign, term.base)
                } else {
                    write!(fmt, " {} {}*{}^x", sign, abs_coeff, term.base)
                });
            }
            Ok(())
        } else {
            write!(fmt, "0")
        }
    }
}

#[cfg(test)]
mod test {
    use num_bigint::{BigUint, BigInt};
    use num_traits::{Zero, pow};
    use super::{Polynomial, Term};

    fn test_int1() -> BigInt {
        BigInt::from(2i32)
    }
    fn test_int2() -> BigInt {
        BigInt::from(5i32)
    }
    fn test_uint1() -> BigUint {
        BigUint::from(12u32)
    }
    fn test_uint2() -> BigUint {
        BigUint::from(25u32)
    }
    fn empty_polynomial() -> Polynomial {
        Polynomial { terms: vec![] }
    }

    #[test]
    fn one_term_test() {
        assert_eq!(Polynomial::one_term(test_int1(), test_uint1()),
                   Polynomial {
                       terms: vec![
                           Term { coeff: test_int1(), base: test_uint1() }
                       ]
                   });
        assert_eq!(Polynomial::one_term(BigInt::zero(), test_uint1()),
                   empty_polynomial());
    }

    #[test]
    fn add_test() {
        let a = Polynomial::one_term(test_int1(), test_uint1());
        let b = Polynomial::one_term(test_int2(), test_uint2());
        let sum = Polynomial {
            terms: vec![
                Term { coeff: test_int1(), base: test_uint1() },
                Term { coeff: test_int2(), base: test_uint2() }
            ]
        };
        assert_eq!(a.clone() + b.clone(), sum);
        assert_eq!(b.clone() + a.clone(), sum);

        let a = Polynomial::one_term(test_int1(), test_uint1());
        let b = Polynomial::one_term(test_int2(), test_uint1());
        let sum = Polynomial {
            terms: vec![
                Term { coeff: test_int1() + test_int2(), base: test_uint1() }
            ]
        };
        assert_eq!(a.clone() + b.clone(), sum);
        assert_eq!(b.clone() + a.clone(), sum);

        let a = Polynomial::one_term(test_int1(), test_uint1());
        let b = Polynomial::one_term(-test_int1(), test_uint1());
        assert_eq!(a.clone() + b.clone(), empty_polynomial());
    }

    #[test]
    fn sub_test() {
        let a = Polynomial::one_term(test_int1(), test_uint1());
        let b = Polynomial::one_term(test_int2(), test_uint2());
        let diff = Polynomial {
            terms: vec![
                Term { coeff: test_int1(), base: test_uint1() },
                Term { coeff: -test_int2(), base: test_uint2() }
            ]
        };
        assert_eq!(a.clone() - b.clone(), diff);
        let diff = Polynomial {
            terms: vec![
                Term { coeff: -test_int1(), base: test_uint1() },
                Term { coeff: test_int2(), base: test_uint2() }
            ]
        };
        assert_eq!(b.clone() - a.clone(), diff);

        let a = Polynomial::one_term(test_int1(), test_uint1());
        let b = Polynomial::one_term(test_int2(), test_uint1());
        let diff = Polynomial {
            terms: vec![
                Term { coeff: test_int1() - test_int2(), base: test_uint1() }
            ]
        };
        assert_eq!(a.clone() - b.clone(), diff);
        let diff = Polynomial {
            terms: vec![
                Term { coeff: test_int2() - test_int1(), base: test_uint1() }
            ]
        };
        assert_eq!(b.clone() - a.clone(), diff);

        assert_eq!(a.clone() - a.clone(), empty_polynomial());
    }

    #[test]
    fn add_assign_test() {
        let a = Polynomial::one_term(test_int1(), test_uint1());
        let b = Polynomial::one_term(test_int2(), test_uint2());
        let mut sum = a.clone();
        sum += b.clone();
        assert_eq!(sum, a.clone() + b.clone());
        let mut sum = b.clone();
        sum += a.clone();
        assert_eq!(sum, b.clone() + a.clone());

        let a = Polynomial::one_term(test_int1(), test_uint1());
        let b = Polynomial::one_term(test_int2(), test_uint1());
        let mut sum = a.clone();
        sum += b.clone();
        assert_eq!(sum, a.clone() + b.clone());
        let mut sum = b.clone();
        sum += a.clone();
        assert_eq!(sum, b.clone() + a.clone());
    }

    #[test]
    fn sub_assign_test() {
        let a = Polynomial::one_term(test_int1(), test_uint1());
        let b = Polynomial::one_term(test_int2(), test_uint2());
        let mut diff = a.clone();
        diff -= b.clone();
        assert_eq!(diff, a.clone() - b.clone());
        let mut diff = b.clone();
        diff -= a.clone();
        assert_eq!(diff, b.clone() - a.clone());

        let a = Polynomial::one_term(test_int1(), test_uint1());
        let b = Polynomial::one_term(test_int2(), test_uint1());
        let mut diff = a.clone();
        diff -= b.clone();
        assert_eq!(diff, a.clone() - b.clone());
        let mut diff = b.clone();
        diff -= a.clone();
        assert_eq!(diff, b.clone() - a.clone());
    }

    #[test]
    fn apply_test() {
        let a = Polynomial::one_term(test_int1(), test_uint1());
        let b = Polynomial::one_term(test_int2(), test_uint2());
        let x = 50usize;
        assert_eq!((a.clone() + b.clone()).apply(x),
                   test_int1() * BigInt::from(pow(test_uint1(), x)) +
                   test_int2() * BigInt::from(pow(test_uint2(), x)));
        assert_eq!((a.clone() - b.clone()).apply(x),
                   test_int1() * BigInt::from(pow(test_uint1(), x)) -
                   test_int2() * BigInt::from(pow(test_uint2(), x)));
    }
}