I'm in a need to optimize this really tiny, but pesky function.
unsigned umod(int a, unsigned b) { while(a < 0) a += b; return a % b; }
Before you cry out "You don't need to optimize it", please keep in mind that this function is called 50% of the entire program lifetime, as it's being called 21495808 times for the smallest test case benchmark.
The function is already being inlined by the compiler so please don't offer to add the inline
keyword.
For a positive integer n, two integers a and b are said to be congruent modulo n (or a is congruent to b modulo n), if a and b have the same remainder when divided by n (or equivalently if a − b is divisible by n ). It can be expressed as a ≡ b mod n. n is called the modulus.
This is the basic formula: dividend = divisor * quotient + remainder From this equation you can calculate the remainder.
If you want to return the opposite, the integer part of a division, in that case you have to use the QUOTIENT function.
"A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type."
This avoids looping:
int tmp = a % b; if (tmp < 0) tmp += b;
Notice that both a and b need to be signed.
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