rand.c 582 B

1234567891011121314151617181920212223242526272829303132333435
  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. int rand_r(unsigned int* seed)
  11. { int32_t X;
  12. X = *seed;
  13. X = A*(X%Q) - R * (int32_t) (X/Q);
  14. if (X < 0)
  15. X += M;
  16. *seed = X;
  17. return X;
  18. }
  19. int rand(void) {
  20. return rand_r(&_seed);
  21. }
  22. void srand(unsigned int i)
  23. {
  24. _seed=i;
  25. }
  26. int random(void) __attribute__((alias("rand")));
  27. void srandom(unsigned int i) __attribute__((alias("srand")));