Skip to content

Instantly share code, notes, and snippets.

@cpylua
Created December 17, 2011 14:10
Show Gist options
  • Save cpylua/1490293 to your computer and use it in GitHub Desktop.
Save cpylua/1490293 to your computer and use it in GitHub Desktop.
CRT random number generator cycle peroid test
#include <stdlib.h>
#include <stdio.h>
/**
* Return the cycle period
*/
int brent_cycle_detect(int seed) {
int power = 1;
int lambda = 1;
int tortoise = seed;
int hare;
srand(seed);
hare = rand();
while (hare != tortoise) {
if (power == lambda) {
tortoise = hare;
power *= 2;
lambda = 0;
}
hare = rand();
lambda++;
}
return lambda;
}
void run_test(int repeat) {
int i;
int seed;
int period = 42;
printf("seed,period\n");
for (i = 0; i < repeat; i++) {
srand(period);
seed = rand();
period = brent_cycle_detect(seed);
printf("%d,%d\n", seed, period);
}
}
int main(int argc, char** argv) {
if (argc != 2) {
printf("usage: %s repear-count\n", argv[0]);
exit(-1);
} else {
int repeat = atoi(argv[1]);
run_test(repeat);
}
return 0;
}
#define _CRT_RAND_S
#include <stdlib.h>
#include <stdio.h>
/**
* Return the cycle period
*/
int brent_cycle_detect(unsigned int seed) {
int power = 1;
int lambda = 1;
unsigned int tortoise;
unsigned int hare;
rand_s(&tortoise);
rand_s(&hare);
while (hare != tortoise) {
if (power == lambda) {
tortoise = hare;
power *= 2;
lambda = 0;
}
rand_s(&hare);
lambda++;
}
return lambda;
}
void run_test(int repeat) {
int i;
int seed;
int period = 42;
printf("seed,period\n");
for (i = 0; i < repeat; i++) {
srand(period);
seed = rand();
period = brent_cycle_detect(seed);
printf("%d,%d\n", seed, period);
}
}
int main(int argc, char** argv) {
if (argc != 2) {
printf("usage: %s repear-count\n", argv[0]);
exit(-1);
} else {
int repeat = atoi(argv[1]);
run_test(repeat);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment