Skip to content

Instantly share code, notes, and snippets.

@xNWDD
Created April 9, 2019 08:53
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 xNWDD/5a58dcc8eb4e417117ae23866d603aaa to your computer and use it in GitHub Desktop.
Save xNWDD/5a58dcc8eb4e417117ae23866d603aaa to your computer and use it in GitHub Desktop.
#include <cstdint>
template<uint16_t d> struct lfm16 { //lemire fast math for 16-bit space https://github.com/lemire/fastmod
enum : uint32_t { M = uint32_t(-1) / d + 1 };
static constexpr uint16_t mod(uint16_t a) { return uint16_t((uint64_t(d) * uint32_t(M * a)) >> 32); }
static constexpr uint16_t div(uint16_t a) { return uint16_t((uint64_t(M) * a) >> 32); }
static constexpr bool mod0(uint16_t a) { return a * M <= M - 1; }
};
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::cout
<< lfm16<32>::div(64) << std::endl
<< lfm16<32>::mod(64) << std::endl
<< lfm16<32>::mod(67) << std::endl
<< lfm16<32>::mod0(64) << std::endl
<< lfm16<32>::mod0(16) << std::endl
<< lfm16<32>::mod0(64*15) << std::endl
;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment