Other than the while loop, Not sure whether the % operation can be optimized as a whole, but the optimization can happen on the pattern of the values for a & b.
If in those 21495808 times the operation is executed.
If the chances of passing a value for a which is less than b ( a < b ) is atleast half of the that.
Adding the following statement will definetly improve the overall performance of the function.
if ( abs(a) < b ) // not specifically the abs function, can be your own implementation.
return 0;
else
return a%b;
If b is a power of 2 for atleast 80% of the cases, we can use bitwise operators as in
return ( abs(a) & (b-1) );
If the numbers are expected to be anything less than that, it would degrade the performance, as we need to verify whether b is power of 2 [ even after using bitwise operators for the same ] for everything.
Even the functionality to achieve abs(a) can be optimized using bitwise operators, with their own limitations, but is faster than verifying whether a is < 0.
n = (a ^ (a >> 31)) - (a >> 31); // instead of n = a < 0 ? -a : a;
There would be more such things, if you can explore.