Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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