Skip to content

Instantly share code, notes, and snippets.

@sup39
Created July 22, 2022 20:14
Show Gist options
  • Save sup39/bcfb56fba0c592d510b63560415e71a4 to your computer and use it in GitHub Desktop.
Save sup39/bcfb56fba0c592d510b63560415e71a4 to your computer and use it in GitHub Desktop.
#include <stdint.h>
uint32_t rng(uint32_t x);
uint32_t rnginv(uint32_t x);
#define mul4k1(a, b) (4*a*b+a+b)
#define d 275878811
#define bdinv 15530683
#define dbinv 317143667
#define qmask 0x7FFFFFFF
static uint32_t mxmodq(uint32_t x) {
uint32_t u = d;
uint32_t ans = 0;
while (x) {
if (x & 1)
ans = mul4k1(ans, u);
u = mul4k1(u, u);
x >>= 1;
}
return ans & qmask;
}
uint32_t rng(uint32_t x) {
return mxmodq(x)*bdinv & qmask;
}
uint32_t rnginv(uint32_t r) {
uint32_t s = dbinv*r & qmask;
uint32_t x = 0;
while (1) {
uint32_t g = mxmodq(x);
if (g == s) return x;
x |= 1 << __builtin_ctz(g-s);
}
return x;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment