1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
|
void divRemain(int& nDivides, int& nRemain, int divisor)
{
// Working Variables
//---------------------------------------------------------
int i(0); // index iterator
int counter(0); // bit counter
bool empty(false); // is-empty trigger
bitset<2> negative = { 0 }; // negative double trigger
// IF, dividend is negative:
if (nDivides < 0)
negative[0] = 1; // trigger
// IF, divisor is negative:
if (divisor < 0)
{
negative[1] = 1; // trigger
divisor *= -1; // negate
}
// Initialise the bitset
bitset<32> bin(nDivides);
// Assign zero value to nDivides and nRemain
//---------------------------------------------------------
nDivides = 0;
nRemain = 0;
// WHILE, bitset is not empty, LOOP:
while (!empty)
{
// IF, 1's place is set:
if (bin[0] == 1)
{
// add 1 to counter
counter++;
// IF, counter is full:
if (counter == divisor)
{
nDivides++; // add 1 to nDivides
counter = 0; // reset counter
}
// set 1's place to zero
bin.set(0, 0);
}
// IF, 1's place is not set:
if (bin[0] == 0)
{
// Search for the next set bit
//---------------------------------------------------------
// WHILE, not at last element, LOOP:
while (i <= 31)
{
// IF, found next set bit:
if (bin[i] == 1)
{
// add 1 to counter
counter++;
// IF, counter is full:
if (counter == divisor)
{
nDivides++; // add 1 to nDivides
counter = 0; // reset counter
}
// unset bit
bin.set(i, 0);
// Record the (bitset - 1)
//---------------------------------------------------------
// WHILE, more than zero, LOOP:
while (i > 0)
{
i--; // iterate down bitset
bin.set(i); // set bit
}
break;
}
// ELSE IF, next set bit not found:
else if (bin[i] == 0 && i != 31)
{
i++; // continue search
continue;
}
// ELSE IF, bitset empty:
else if (bin[i] == 0 && i == 31)
{
empty = true; // trigger
break;
}
}
}
// IF, bitset is empty and counter is not zero:
if (empty && counter != 0)
nRemain = counter; // empty counter into nRemainder
// IF, result is negative and the bitset is empty:
if (negative.any() && !negative.all() && empty)
{
nDivides *= -1; // negate nDivides
nRemain *= -1; // negate nRemain
}
}
}
|