use std::cmp::Ordering;
use std::fmt;
use std::ops::{Add, AddAssign, Div, Mul, Sub, SubAssign};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub struct Q {
n: i64,
d: i64,
}
fn gcd(a: i64, b: i64) -> i64 {
let (mut a, mut b) = (a.abs(), b.abs());
while b != 0 {
(a, b) = (b, a % b);
}
a.max(1)
}
impl Q {
pub const ZERO: Q = Q { n: 0, d: 1 };
pub const ONE: Q = Q { n: 1, d: 1 };
pub fn new(n: i64, d: i64) -> Q {
let (n, d) = if d < 0 { (-n, -d) } else { (n, d) };
let g = gcd(n, d);
Q { n: n / g, d: d / g }
}
pub fn int(n: i64) -> Q {
Q { n, d: 1 }
}
pub fn is_power_of_two(self) -> bool {
self.n > 0 && (self.n as u64).is_power_of_two() && (self.d as u64).is_power_of_two()
}
pub fn to_f64(self) -> f64 {
self.n as f64 / self.d as f64
}
pub fn floor_div(self, o: Q) -> i64 {
(self.n * o.d).div_euclid(o.n * self.d)
}
pub fn is_zero(self) -> bool {
self.n == 0
}
}
impl Add for Q {
type Output = Q;
fn add(self, o: Q) -> Q {
Q::new(self.n * o.d + o.n * self.d, self.d * o.d)
}
}
impl Sub for Q {
type Output = Q;
fn sub(self, o: Q) -> Q {
Q::new(self.n * o.d - o.n * self.d, self.d * o.d)
}
}
impl Mul for Q {
type Output = Q;
fn mul(self, o: Q) -> Q {
Q::new(self.n * o.n, self.d * o.d)
}
}
impl Div for Q {
type Output = Q;
fn div(self, o: Q) -> Q {
Q::new(self.n * o.d, self.d * o.n)
}
}
impl AddAssign for Q {
fn add_assign(&mut self, o: Q) {
*self = *self + o;
}
}
impl SubAssign for Q {
fn sub_assign(&mut self, o: Q) {
*self = *self - o;
}
}
impl Ord for Q {
fn cmp(&self, o: &Q) -> Ordering {
(self.n * o.d).cmp(&(o.n * self.d))
}
}
impl PartialOrd for Q {
fn partial_cmp(&self, o: &Q) -> Option<Ordering> {
Some(self.cmp(o))
}
}
impl std::iter::Sum for Q {
fn sum<I: Iterator<Item = Q>>(it: I) -> Q {
it.fold(Q::ZERO, |a, b| a + b)
}
}
impl fmt::Display for Q {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.d == 1 {
write!(f, "{}", self.n)
} else {
write!(f, "{}/{}", self.n, self.d)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn arithmetic_stays_in_lowest_terms() {
assert_eq!(Q::new(2, 4) + Q::new(1, 4), Q::new(3, 4));
assert_eq!(Q::new(3, 2).floor_div(Q::ONE), 1);
assert!(Q::new(1, 3) < Q::new(1, 2));
assert_eq!([Q::new(1, 2), Q::new(1, 2)].into_iter().sum::<Q>(), Q::ONE);
}
#[test]
fn a_power_of_two_is_one_note_value() {
assert!(Q::new(1, 8).is_power_of_two() && Q::int(4).is_power_of_two());
assert!(!Q::new(3, 8).is_power_of_two() && !Q::new(2, 3).is_power_of_two());
assert!(!Q::ZERO.is_power_of_two());
}
}