rustinteger-division

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.


Solution

  • 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.