I am relatively new to programming, and after going through some of the questions asked on this subject, I still could not find an answer.
As I understand it, the %
operator in C++ can be rewritten in a number of ways, some of which seem to perform better as indicated by some users here:
Built-in mod ('%') vs custom mod function: improve the performance of modulus operation
Now if I understand correctly, arithmetic operations on integers - such as +
and -
are faster than *
and /
when we think about multiplication as repeated addition for instance( this is commonly mentioned in threads I have read).
So, why wouldn't something like the following function be faster than %
:
int mod(int a, int b)
{
int s = a;
while(s < b)
{
s += a;
}
return a - (s - b);
}
As I am quite new to programming and have little knowledge in how things are implemented by compilers- I am not sure what way would be appropriate to test this, and whether results might vary greatly depending on the compiler and implementations.