Implement a linear congruential generator with a seed kept in a file-scope static variable, a function to set the seed, and one to get the next number from 0 to 99.
Solution
main.c
#include <stdint.h>
#include <stdio.h>
static uint32_t state = 1; /* private to this file */
void my_srand(uint32_t seed) { state = seed; }
int my_rand100(void) {
state = state * 1664525u + 1013904223u; /* wraps modulo 2^32: well-defined for unsigned */
return (int) (state >> 16) % 100; /* the high bits are the most random */
}
int main(void) {
my_srand(42);
for (int i = 0; i < 5; i++)
printf("%d ", my_rand100());
printf("\n");
my_srand(42); /* same seed, same sequence */
printf("%d\n", my_rand100());
return 0;
}
Output Verified by compiling and running
37 75 32 85 19
37
Unsigned 32-bit arithmetic wraps modulo 2³², which is exactly what the generator needs. The static state is hidden from other files, and re-seeding reproduces the same sequence – useful for tests. (Not for cryptography.)
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!