Skip to content

Instantly share code, notes, and snippets.

@orlp
Last active August 29, 2015 14:20
Show Gist options
  • Save orlp/4f30c164406b2c92bd51 to your computer and use it in GitHub Desktop.
Save orlp/4f30c164406b2c92bd51 to your computer and use it in GitHub Desktop.
// Computes cR such that cR = aR * bR (mod n) with R = 2**64.
inline uint64_t montmul64(uint64_t aR, uint64_t bR, uint64_t n, uint64_t nneginv) {
uint64_t Th, Tl, m, mnh, mnl, th;
std::tie(Th, Tl) = op::mulu64(aR, bR);
m = Tl * nneginv;
std::tie(mnh, mnl) = op::mulu64(m, n);
bool lc = Tl + mnl < Tl;
th = Th + mnh + lc;
bool hc = (th < Th) || (th == Th && lc);
if (hc > 0 || th >= n) th = th - n;
return th;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment