Skip to content

Instantly share code, notes, and snippets.

@XI64
Last active July 26, 2021 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XI64/ea63f7d7cd8a3a2c9cb4b4c3c3809d8a to your computer and use it in GitHub Desktop.
Save XI64/ea63f7d7cd8a3a2c9cb4b4c3c3809d8a to your computer and use it in GitHub Desktop.
speedy mod inverses for 2**48
#include <iostream>
const uint64_t MASK = 0xffffffffffffL;
//Credits : Matthew Bolan for the following Function
static inline uint64_t modInverse(uint64_t a,uint64_t k){
uint64_t x = (((a << 2) ^ (a << 1)) & 8) ^ a;
x += x - a * x * x;
x += x - a * x * x;
x += x - a * x * x;
x += x - a * x * x;
return x & MASK;
}
//My implementation
static inline uint64_t mod_inverse_1(uint64_t a)
{
uint64_t x,t;
x = (((a << 2) ^ (a << 1)) & 8) ^ a;
x *= 2-a*x;
x *= 2-a*x;
x *= 2-a*x;
x *= 2-a*x;
return x & MASK;
}
int main(int argc, char const *argv[])
{
uint64_t hold = modInverse(555666999, 48);
uint64_t hold2 = mod_inverse_1(555666999);
std::cout << "modIverse of 555666999 with mod 2^48 : " << hold << std::endl;
std::cout << "modInverse of 555666999 with mod 2^48 : " << hold2 << std::endl;
return 0;
}
@XI64
Copy link
Author

XI64 commented Feb 16, 2021

Two functions for checking validity.

First function credits : Matthew Bolan (mjtb49 on github)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment