I found some promising looking code on one of the questions linked to the one lugnut gave:
int mod(int a, int b)
{
int x = b;
while (!(a < b))
b <<= 1;
while (!(a < x))
{
while(a < b)
b >>= 1;
a -= b;
}
return a;
}
I'm going to implement fast dividing by single digit numbers soon and then implementing this will be a trivial task, and should outperform the naive division method.
EDIT: optimizations, wrote the comparisons using only less than and not (which are very easy to calculate) and multiplying by 0.5 with third parameter -1 should work just as fast as the method I had in mind for dividing by 2. I'm writing the method now.
EDIT 2: Finished writing the code. Could someone test it out for me?
function Math_Mod(%a, %b)
{
%x = %b;
while(!alessthanb(%a, %b))
%b = Math_Multiply(%b, 2);
while(!alessthanb(%a, %x))
{
while(alessthanb(%a, %b))
%b = Math_Multiply(%b, 0.5, -1);
%a = Math_Subtract(%a, %b);
}
return %a;
}
function alessthanb(%a, %b)
{
%c = strLen(%a); %d = strLen(%b);
//Only do character-by-character comparisons if lengths are equal
if(%c < %d)
return true;
else if(%d < %c)
return false;
//Exact equals check
if(%a $= %b)
return false;
for(%x = 0; %x < %c; %x++)
{
%y = getSubStr(%a, %x, 1); %z = getSubStr(%b, %x, 1);
if(%y < %z)
return true;
else if(%y > %z)
return false;
}
}