/* Written in 2021 by Sebastiano Vigna (vigna@acm.org)
To the extent possible under law, the author has dedicated all copyright
and related and neighboring rights to this software to the public domain
worldwide. This software is distributed without any warranty.
See . */
#include
#include
/* This is a Marsaglia multiply-with-carry generator with period
approximately 2^127. It is close in speed to a scrambled linear
generator, as its only 128-bit operations are a multiplication and sum;
is an excellent generator based on congruential arithmetic.
As all MWC generators, it simulates a multiplicative LCG with
prime modulus m = 0xff3a275c007b8ee5ffffffffffffffff and
multiplier given by the inverse of 2^64 modulo m. The modulus has a
particular form, which creates some theoretical issues, but at this
size a generator of this kind passes all known statistical tests. For a
generator of the same type with stronger theoretical guarantees
consider a Goresky-Klapper generalized multiply-with-carry generator.
*/
#define MWC_A1 0xff3a275c007b8ee6
/* The state must be initialized so that 0 < c < MWC_A1 - 1. */
uint64_t x, c;
uint64_t inline next() {
const __uint128_t t = MWC_A1 * (__uint128_t)x + c;
c = t >> 64;
return x = t;
}
/* The following jump functions use a minimal multiprecision library. */
#define MP_SIZE 3
#include "mp.c"
static uint64_t mod[MP_SIZE] = { 0xffffffffffffffff, MWC_A1 - 1 };
/* This is the jump function for the generator. It is equivalent
to 2^64 calls to next(); it can be used to generate 2^64
non-overlapping subsequences for parallel computations.
Equivalent C++ Boost multiprecision code:
cpp_int b = cpp_int(1) << 64;
cpp_int m = MWC_A1 * b - 1;
cpp_int r = cpp_int("0xad780dfca54acd22e2e6349c6291cf7c");
cpp_int s = ((x + c * b) * r) % m;
x = uint64_t(s);
c = uint64_t(s >> 64);
*/
void jump(void) {
static uint64_t jump[MP_SIZE] = { 0xe2e6349c6291cf7c, 0xad780dfca54acd22 };
uint64_t state[MP_SIZE] = { x, c };
mul(state, jump, mod);
x = state[0];
c = state[1];
}
/* This is the long-jump function for the generator. It is equivalent to
2^96 calls to next(); it can be used to generate 2^32 starting points,
from each of which jump() will generate 2^32 non-overlapping
subsequences for parallel distributed computations.
Equivalent C++ Boost multiprecision code:
cpp_int b = cpp_int(1) << 64;
cpp_int m = MWC_A1 * b - 1;
cpp_int r = cpp_int("0x1e6d528a48b8844b7744089d9c414aeb");
cpp_int s = ((x + c * b) * r) % m;
x = uint64_t(s);
c = uint64_t(s >> 64);
*/
void long_jump(void) {
static uint64_t long_jump[MP_SIZE] = { 0x7744089d9c414aeb, 0x1e6d528a48b8844b };
uint64_t state[MP_SIZE] = { x, c };
mul(state, long_jump, mod);
x = state[0];
c = state[1];
}