C Program to Implement Linear Congruential Method for Generating Pseudo Random Number

This is a C Program to generate random numbers using Linear Congruential Generator. The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula:
r{n + 1} = a x rn + c mod m
Where:
r0 is a seed.
r1, r2, r3, …, are the random numbers.
a, c, m are constants.

Here is source code of the C Program to Implement the linear congruential generator for Pseudo Random Number Generation. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include <stdio.h>
  2.  
  3. /* always assuming int is at least 32 bits */
  4. int rand();
  5. int rseed = 0;
  6.  
  7. inline void srand(int x) {
  8.     rseed = x;
  9. }
  10.  
  11. #ifndef MS_RAND
  12. #define RAND_MAX ((1U << 31) - 1)
  13.  
  14. inline int rand() {
  15.     return rseed = (rseed * 1103515245 + 12345) & RAND_MAX;
  16. }
  17.  
  18. #else /* MS rand */
  19.  
  20. #define RAND_MAX_32 ((1U << 31) - 1)
  21. #define RAND_MAX ((1U << 15) - 1)
  22.  
  23. inline int rand()
  24. {
  25.     return (rseed = (rseed * 214013 + 2531011) & RAND_MAX_32) >> 16;
  26. }
  27.  
  28. #endif/* MS_RAND */
  29.  
  30. int main() {
  31.     int i;
  32.     printf("rand max is %d\n", RAND_MAX);
  33.  
  34.     for (i = 0; i < 10; i++)
  35.         printf("%d\n", rand());
  36.  
  37.     return 0;
  38. }

Output:

$ gcc LCG.c
$ ./a.out
 
rand max is 2147483647
12345
1406932606
654583775
1449466924
229283573
1109335178
1051550459
1293799192
794471793
551188310

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data Structures and Algorithms.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.