I have the following code I am working on, but I think it can be optimised further probably by improving the min/max variable selection, (see below).
The idea is to not use actual division, ('/'), to get the quotient and remainder.
I think there could be a way to improve performance by further minimising the number of loops.
NB The idea is not to have a function faster than Num/Den but rather to have the function running as efficiently as possible.
void DivisionDivideAndConquer(const unsigned int Num, const unsigned int Den, unsigned int& Quo, unsigned int& Rem)
{
// short cuts
if (Num < Den)
{
Quo = 0;
Rem = Den;
return;
}
// R = N - D * Q where 0 <= R < |D|
// getting us started
unsigned int min = 0;
unsigned int max = Num;
for (;;)
{
unsigned int number = static_cast<unsigned int>((min + max) * 0.5);
int possibleRemainder = (Num - (Den * number));
// if too small then we have a new max
if (possibleRemainder < 0) {
if (number == max) {
max = max - 1;
}
else {
max = number;
}
}
// too big we have a new min
else if(possibleRemainder >= static_cast<int>(Den) )
{
if (number == max) {
min = min + 1;
}
else {
min = number;
}
}
else
{
// got it!
Quo = number;
Rem = static_cast<unsigned int>(possibleRemainder);
break;
}
}
}
int main(int argc, char** argv)
{
unsigned int Quo = 0;
unsigned int Rem = 0;
DivisionDivideAndConquer(12, 4, Quo, Rem); // Q=3, R=0
// ...
DivisionDivideAndConquer(12, 9, Quo, Rem); // Q=1, R=3
}