Consider a routine that counts by successive divide w/ remainder operations.
Starting with a 64-bit dividend, the routine divides by a constant divisor.
If the remainder is 0, the routine returns.
Otherwise, a new dividend is constructed by multiplying the remainder by 2^32 and adding the integer quotient.
In code:
/// ULong - 64 bit, unsigned
/// UInt - 32 bit, unsigned
const UInt Divisor;
int TrickyCounter( ULong Dividend)
{
int count = 0;
Ulong Quotient;
UInt Remainder;
do {
Quotient = Dividend/Divisor;
Remainder = Dividend%Divisor;
assert((Quotient >> 32) == 0);
count = count + 1;
Dividend = ((ULong)Remainder << 32) + Quotient;
} while (Remainder != 0);
return count;
}
With an arbitrary Divisor, is there a preferably non-iterating method to calculate the necessary Dividend to get the desired count?
For many initial dividends, this seems to quickly hit the "Assert" condition. Would some dividends cause this to loop forever?
If, instead of a count, the routine returns the quotient, can I calculate the Dividend to produce the number I want returned?
Uint TrickyNumber( ULong Dividend, int count)
{
Ulong Quotient = 0;
UInt Remainder;
while (count > 0)
Quotient = Dividend/Divisor;
Remainder = Dividend%Divisor;
assert((Quotient >> 32) == 0);
count = count - 1;
Dividend = ((ULong)Remainder << 32) + Quotient;
}
return (UInt)Quotient;
}