How to muldiv in D?

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Nov 21 15:43:09 PST 2016


On 11/21/2016 11:16 AM, Kagamin wrote:
> Can't find a function for it.

Here is a draft adapted from the following page

 
http://stackoverflow.com/questions/14872499/is-there-an-equivalent-to-muldiv-for-linux

This draft works for signed types:

T mulDiv(T)(T number, T numerator, T denominator) {
     static if (is (T == long)) {
         static assert("Sorry, can't support long");
     }
     else static if (is (T == int)) {
         alias InterimT = long;
     }
     else {
         alias InterimT = int;
     }

     InterimT ret = number;
     ret *= numerator;
     ret /= denominator;
     return cast(T)ret;
}

void main() {
     int number = int.max / 2;
     int numerator = 42;
     int denominator = numerator * 2;

     const correctResult = int.max / 4;
     const wrongResult = number * numerator / denominator;

     assert(mulDiv(number, numerator, denominator) == correctResult);
     assert(wrongResult != correctResult);
}

Ali



More information about the Digitalmars-d-learn mailing list