Compute (a*b)%n FAST for 64-bit unsigned arguments in C(++) on x86-64 platforms?

前端 未结 5 695
走了就别回头了
走了就别回头了 2021-01-15 12:35

I\'m looking for a fast method to efficiently compute  (ab) modulo n  (in the mathematical sense of that) for

5条回答
  •  情深已故
    2021-01-15 13:02

    This intrinsic is named __mul128.

    typedef unsigned long long BIG;
    
    // handles only the "hard" case when high bit of n is set
    BIG shl_mod( BIG v, BIG n, int by )
    {
        if (v > n) v -= n;
        while (by--) {
            if (v > (n-v))
                v -= n-v;
            else
                v <<= 1;
        }
        return v;
    }
    

    Now you can use shl_mod(B, n, 64)

提交回复
热议问题