Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsigned modulos: alternative approach?

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.

like image 590
LiraNuna Avatar asked Feb 24 '10 03:02

LiraNuna


People also ask

What does a ≡ b mod n mean?

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.

How do you calculate modulus without operator?

This is the basic formula: dividend = divisor * quotient + remainder From this equation you can calculate the remainder.

How do you find the opposite of a mod?

If you want to return the opposite, the integer part of a division, in that case you have to use the QUOTIENT function.

Can unsigned int overflow?

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


1 Answers

This avoids looping:

int tmp = a % b; if (tmp < 0) tmp += b; 

Notice that both a and b need to be signed.

like image 115
Tronic Avatar answered Sep 21 '22 21:09

Tronic