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

前端 未结 5 644
走了就别回头了
走了就别回头了 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:16

    7 years later, I got a solution working in Visual Studio 2019

    #include 
    #include 
    #pragma intrinsic(_umul128)
    #pragma intrinsic(_udiv128)
    
    // compute (a*b)%n with 128-bit intermediary result
    // assumes n>0  and  a*b < n * 2**64 (always the case when a<=n || b<=n )
    inline uint64_t mulmod(uint64_t a, uint64_t b, uint64_t n) {
      uint64_t r, s = _umul128(a, b, &r);
      (void)_udiv128(r, s, n, &r);
      return r;
    }
    
    // compute (a*b)%n with 128-bit intermediary result
    // assumes n>0, works including if a*b >= n * 2**64
    inline uint64_t mulmod1(uint64_t a, uint64_t b, uint64_t n) {
      uint64_t r, s = _umul128(a % n, b, &r);
      (void)_udiv128(r, s, n, &r);
      return r;
    }
    

提交回复
热议问题