How can I perform ceiling division on an integer? I want to avoid converting to a floating point value.
For example, 7 / 4 should return 2, not 1.
Rust 1.73 Update:
There is u32::div_ceil() on stable now.
While i32::div_ceil() is unstable on nightly.
Rust stable v1.61.0 branch: ceil(a/b) is (a + b - 1) / b if you know that that addition won't overflow.
From the Rust standard library (minimum version 1.73)
u32: div_ceil
u64: div_ceil
// pub const fn div_ceil(self, rhs: Self) -> Self;
// Calculates the quotient of self and rhs,
// rounding the result towards positive infinity.
let integer: u32 = 122023;
let result = integer.div_ceil(10000); // 13
assert_eq!(7_u32.div_ceil(4), 2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With