Skip to content

Instantly share code, notes, and snippets.

@lemire
Created July 12, 2018 20:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lemire/b9596313593dcb6aa311f5e5aa60f517 to your computer and use it in GitHub Desktop.
Save lemire/b9596313593dcb6aa311f5e5aa60f517 to your computer and use it in GitHub Desktop.
fast alternative to the modulo reduction (code sample)
#include <iostream>
#include <cstdint>
using namespace std;
// we are going to generate random numbers using
// an xorshift generator
static uint32_t xorshift_y;
void xorshift32_seed(uint32_t seed) { xorshift_y = seed;}
uint32_t xorshift32(void) {
xorshift_y ^= (xorshift_y << 13);
xorshift_y ^= (xorshift_y >> 17);
return xorshift_y ^= (xorshift_y << 5);
}
uint32_t reduce(uint32_t x, uint32_t N) {
return (((uint64_t)x * (uint64_t)N) >> 32);
}
int main() {
// seeding the rng
xorshift32_seed(1234);
// we print 10 numbers
for(int k = 0; k < 10; k++)
cout<< reduce(xorshift32(), 7) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment