Integer division but also return whether result was floored/rounded down

Hi, I currently have code like this:

let a: u64 = 10;
let b: u64 = 4;
let div = a / b;
// check if div was rounded down (which e.g. it was here)

Is there a single division instruction/function in rust (maybe in a 3rd party crate) that lets me receive whether the result was rounded down as well as the result of the division at the same time? Something like:

let (div_result, rounded_down) = div(a, b);

where rounded_down is a bool?



You will need to compute a % b != 0 separately.

1 Like

Do you know if it is more efficient to use div_rem or to calculate a % b != 0 separately?

They're the same thing.

fn div_rem(&self, other: &Self) -> (Self, Self) {
                (*self / *other, *self % *other)

LLVM is smart enough to optimize it to just one division:


So does that mean you would recommend using div_rem over doing it manually, even though they are semantically the same, because this groups the commands together and, therefore, might help llvm to recognize it can do it in one instruction?

Be aware that optimizers are very, very good at "peephole" reasoning - just about any modern compiler should be able to spot the intent behind: (a / b, a % b) and optimize it perfectly. As seen in Matt Godbolt's Compiler Explorer:

As a rule of thumb, you can expect the optimizer to spot all of this sort of "trivial" optimization in a single function, and do the right thing - and if you're not sure, try it and look at the assembly.


LLVM is good about that with primitive types, but for something like BigInt, it's better to use the explicitly combined operation.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.