pub mod add;
pub mod index;
pub mod iter;
pub mod math;
pub mod mul;
pub mod rem;
pub mod sub;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Polynomial {
coeffs: Vec<isize>,
}
impl Polynomial {
pub fn new(coeffs: Vec<isize>) -> Self {
let mut output = Self { coeffs };
output.reduce();
output
}
pub fn zero() -> Self {
Self { coeffs: Vec::new() }
}
pub fn constant(i: isize) -> Self {
if i == 0 {
Self::zero()
} else {
Self { coeffs: vec![i] }
}
}
pub fn degree(&self) -> isize {
(self.coeffs.len() as isize) - 1
}
pub fn is_zero(&self) -> bool {
self.degree() == -1
}
pub fn coeffs(&self) -> &Vec<isize> {
&(self.coeffs)
}
pub fn coeffs_mut(&mut self) -> &mut Vec<isize> {
&mut (self.coeffs)
}
fn reduce(&mut self) {
while self.coeffs.last() == Some(&0) {
self.coeffs.pop();
}
}
}
impl std::fmt::Display for Polynomial {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut s = String::new();
if self.is_zero() {
s += &format!("{}", 0);
} else {
let mut plus_flag = false;
for (n, &i) in self.coeffs.iter().enumerate().rev() {
if i != 0 {
if plus_flag {
if i < 0 {
s += " - ";
} else {
s += " + "
}
}
if n == 0 {
s += &format!("{}", if plus_flag { i.abs() } else { i });
} else if n == 1 {
if i == 1 {
s += "x";
} else if i == -1 {
s += &format!("{}x", if plus_flag { "" } else { "-" });
} else {
s += &format!("{}x", if plus_flag { i.abs() } else { i });
}
} else if i == 1 {
s += &format!("x^{}", n);
} else if i == -1 {
s += &format!("{}x^{}", if plus_flag { "" } else { "-" }, n);
} else {
s += &format!("{}x^{}", if plus_flag { i.abs() } else { i }, n);
}
plus_flag = true;
}
}
}
write!(f, "{}", s)
}
}
#[macro_export]
macro_rules! poly {
() => (
Polynomial::zero();
);
($($x:expr),*) => (
Polynomial::new(vec![$($x),*]);
)
}
#[cfg(test)]
mod tests {
use crate::{poly, Polynomial};
#[test]
fn it_works() {
let mut quadratic = poly![1, 2, 1]; let linear = poly![-6, 1]; assert_eq!(&quadratic + &linear, poly![-5, 3, 1]);
assert_eq!(&quadratic - &linear, poly![7, 1, 1]);
assert_eq!(&quadratic * &linear, poly![-6, -11, -4, 1]);
quadratic -= &linear;
assert_eq!(quadratic, poly![7, 1, 1]);
quadratic += &linear;
assert_eq!(quadratic, poly![1, 2, 1]);
quadratic *= &linear;
assert_eq!(quadratic, poly![-6, -11, -4, 1]);
assert_eq!(quadratic.derivative(), poly![-11, -8, 3]);
let mut another = poly![1, 3, 3, 1]; let pair = poly![-5, 4, 2]; assert_eq!(&another + &pair, poly![-4, 7, 5, 1]);
assert_eq!(&another - &pair, poly![6, -1, 1, 1]);
assert_eq!(&another * &pair, poly![-5, -11, -1, 13, 10, 2]);
another -= &pair;
assert_eq!(another, poly![6, -1, 1, 1]);
another += &pair;
assert_eq!(another, poly![1, 3, 3, 1]);
another *= &pair;
assert_eq!(another, poly![-5, -11, -1, 13, 10, 2]);
assert_eq!(another.derivative(), poly![-11, -2, 39, 40, 10]);
}
}