In C and C++, I want to divide and mod a signed integer by a positive integer such that the div rounds towards negative infinity and the mod always returns nonnegative.
For the division I have:
int64_t SignedDiv(int64_t A_signed, int64_t B_positive) {
return A_signed / B_positive - (A_signed % B_positive < 0);
}
which is taken from this answer to a similar question.
For the mod I have:
int64_t SignedMod(int64_t A_signed, int64_t B_positive) {
return A_signed - B_positive * SignedDiv(A_signed, B_positive);
}
which seems terrible. Is there a way to rewrite SignedMod
such that it will return the same thing (and is equally portable) but is more efficient?
Here is the compilation output on godbolt: