Created
November 18, 2017 18:42
-
-
Save unprovable/cb2f85e0702cb3d132dc5f0073f2f77a to your computer and use it in GitHub Desktop.
Arduino LCG play-set
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 <stdlib.h> | |
#include <stdio.h> | |
static int do_rand(unsigned long *ctx) | |
{ | |
/* | |
* Compute x = (7^5 * x) mod (2^31 - 1) | |
* wihout overflowing 31 bits: | |
* (2^31 - 1) = 127773 * (7^5) + 2836 | |
* From "Random number generators: good ones are hard to find", | |
* Park and Miller, Communications of the ACM, vol. 31, no. 10, | |
* October 1988, p. 1195. | |
*/ | |
long hi, lo, x; | |
x = *ctx; | |
/* Can't be initialized with 0, so use another value. */ | |
if (x == 0) | |
x = 123459876L; | |
hi = x / 127773L; | |
lo = x % 127773L; | |
x = 16807L * lo - 2836L * hi; | |
if (x < 0) | |
x += 0x7fffffffL; | |
return ((*ctx = x) % ((unsigned long)RAND_MAX + 1)); | |
} | |
static unsigned long next = 1; | |
int rand(void) | |
{ | |
return do_rand(&next); | |
} | |
void srand(unsigned int seed) | |
{ | |
next = seed; | |
} | |
int main(int argc, char **argv) | |
{ | |
char *p; | |
long conv = strtol(argv[1], &p, 10); | |
srand(conv); // seed with input | |
unsigned long start = rand(); // get starting number | |
if ((start & 0xffff) == 0){ | |
printf("%04x\n", start); | |
} | |
long unsigned int t; | |
//for (int i=0; i<8000000; i++) { | |
while(1){ | |
t = rand(); | |
if (t == start){ | |
printf("We are done!"); | |
return 0; | |
} | |
if ((t & 0xffff) == 0){ | |
printf("%04x\n", t); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment