Improving on provided answer (this reduces overflow when b
is big):
int64_t muldiv64(const int64_t a, const int64_t b, const int64_t d)
{
/* find the integer and remainder portions of x/d */
const int64_t diva = a / d;
const int64_t moda = a % d;
const int64_t divb = b / d;
const int64_t modb = b % d;
return diva * b + moda * divb + moda * modb / d;
}
there is no need to write weird code to avoid using the modulus operation: the compiler can do the substitution and you can have a more readable code.
edit:
Any more complicated code is probably not worth to look into. If more precision is needed probably the good idea is moving to 128 bit arithmetic or use arbitrary precision integer libraries (see http://sourceforge.net/projects/cpp-bigint/)