Skip to content

Commit 21717a0

Browse files
committed
Add linear congruential PRNG example program
1 parent a56b839 commit 21717a0

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

LinearCongruentialGenerator.c

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// A basic implementation of a linear congruential pseudorandom number generator in C
2+
3+
#include <stdio.h>
4+
#include <time.h>
5+
#include <math.h>
6+
7+
struct lcg_rand {
8+
unsigned int modulus;
9+
unsigned int multiplier;
10+
unsigned int increment;
11+
unsigned int seed;
12+
unsigned int last;
13+
};
14+
15+
struct lcg_rand new_generator(unsigned int modulus, unsigned int multiplier, unsigned int increment) {
16+
struct lcg_rand random;
17+
random.modulus = modulus;
18+
random.multiplier = multiplier;
19+
random.increment = increment;
20+
random.seed = time(NULL);
21+
random.last = random.seed;
22+
return random;
23+
}
24+
25+
int random(struct lcg_rand * random) {
26+
int number = ((random->multiplier * random->last) + random->increment) % random->modulus;
27+
random->last = number;
28+
return number;
29+
}
30+
31+
int main() {
32+
struct lcg_rand rng = new_generator(pow(2, 31), 1103515245, 12345);
33+
for (int i = 0; i < 10; i++) {
34+
printf("%d\n", random( & rng));
35+
}
36+
return 0;
37+
}

0 commit comments

Comments
 (0)