Trait rug::ops::DivRounding
source · pub trait DivRounding<Rhs = Self> {
type Output;
fn div_trunc(self, rhs: Rhs) -> Self::Output;
fn div_ceil(self, rhs: Rhs) -> Self::Output;
fn div_floor(self, rhs: Rhs) -> Self::Output;
fn div_euc(self, rhs: Rhs) -> Self::Output;
}
Expand description
Rounding variants of division.
Examples
use rug::ops::DivRounding;
struct I(i32);
impl DivRounding<i32> for I {
type Output = i32;
fn div_trunc(self, rhs: i32) -> i32 {
self.0 / rhs
}
fn div_ceil(self, rhs: i32) -> i32 {
let (q, r) = (self.0 / rhs, self.0 % rhs);
let change = if rhs > 0 { r > 0 } else { r < 0 };
if change {
q + 1
} else {
q
}
}
fn div_floor(self, rhs: i32) -> i32 {
let (q, r) = (self.0 / rhs, self.0 % rhs);
let change = if rhs > 0 { r < 0 } else { r > 0 };
if change {
q - 1
} else {
q
}
}
fn div_euc(self, rhs: i32) -> i32 {
let (q, r) = (self.0 / rhs, self.0 % rhs);
if r < 0 {
if rhs < 0 {
q + 1
} else {
q - 1
}
} else {
q
}
}
}
assert_eq!(I(-10).div_trunc(-3), 3);
assert_eq!(I(-10).div_ceil(-3), 4);
assert_eq!(I(-10).div_floor(-3), 3);
assert_eq!(I(-10).div_euc(-3), 4);