Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform ceiling division?

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.

like image 621
Dogunbound hounds Avatar asked Dec 06 '25 01:12

Dogunbound hounds


2 Answers

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.

like image 131
Dogunbound hounds Avatar answered Dec 08 '25 21:12

Dogunbound hounds


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);

like image 35
Claudio Fsr Avatar answered Dec 08 '25 22:12

Claudio Fsr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!