Created
July 22, 2022 20:14
-
-
Save sup39/bcfb56fba0c592d510b63560415e71a4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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