Unsigned modulos: alternative approach?

c, c++, math, optimization

Solution

This should do it:

unsigned umod(int a, unsigned b)
{
    if (a < 0)
    {
        unsigned r = (-a % b);
        if (r)
            return b - r;
        else
            return 0;
    }
    else
        return a % b;
}

Tested to match original. Limitation is that `a > INT_MIN` on 2s complement machines.

Problem

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.

Original source

Related problems