Fastest way to calculate a 128-bit integer modulo a 64-bit integer

后端 未结 13 1801
谎友^
谎友^ 2020-12-01 00:15

I have a 128-bit unsigned integer A and a 64-bit unsigned integer B. What\'s the fastest way to calculate A % B - that is the (64-bit) remainder from dividing A

13条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 00:47

    You can use the division version of Russian Peasant Multiplication.

    To find the remainder, execute (in pseudo-code):

    X = B;
    
    while (X <= A/2)
    {
        X <<= 1;
    }
    
    while (A >= B)
    {
        if (A >= X)
            A -= X;
        X >>= 1;
    }
    

    The modulus is left in A.

    You'll need to implement the shifts, comparisons and subtractions to operate on values made up of a pair of 64 bit numbers, but that's fairly trivial (likely you should implement the left-shift-by-1 as X + X).

    This will loop at most 255 times (with a 128 bit A). Of course you need to do a pre-check for a zero divisor.

提交回复
热议问题