rand.c 620 B

123456789101112131415161718192021222324252627282930313233343536
  1. #include <stdlib.h>
  2. #include <stdint.h>
  3. #include <sys/types.h>
  4. static unsigned int seed=1;
  5. /* Knuth's TAOCP section 3.6 */
  6. #define M ((1U<<31) -1)
  7. #define A 48271
  8. #define Q 44488 // M/A
  9. #define R 3399 // M%A; R < Q !!!
  10. // FIXME: ISO C/SuS want a longer period
  11. int rand_r(unsigned int* seed)
  12. { int32_t X;
  13. X = *seed;
  14. X = A*(X%Q) - R * (int32_t) (X/Q);
  15. if (X < 0)
  16. X += M;
  17. *seed = X;
  18. return X;
  19. }
  20. int rand(void) {
  21. return rand_r(&seed);
  22. }
  23. void srand(unsigned int i)
  24. {
  25. seed=i;
  26. }
  27. int random(void) __attribute__((alias("rand")));
  28. void srandom(unsigned int i) __attribute__((alias("srand")));