rand.c 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #ifdef ZX81_RNG
  2. /*
  3. * This is my favorite tiny RNG, If you had a ZX81 you may recognise it :-)
  4. * (RdeBath)
  5. */
  6. #include <stdlib.h>
  7. #define MAXINT (((unsigned)-1)>>1)
  8. static unsigned int sseed = 0;
  9. int rand()
  10. {
  11. return (sseed = (((sseed + 1L) * 75L) % 65537L) - 1) & MAXINT;
  12. }
  13. void srand(seed)
  14. unsigned int seed;
  15. {
  16. sseed = seed;
  17. }
  18. #else
  19. /*
  20. * This generator is a combination of three linear congruential generators
  21. * with periods or 2^15-405, 2^15-1041 and 2^15-1111. It has a period that
  22. * is the product of these three numbers.
  23. */
  24. static int seed1 = 1;
  25. static int seed2 = 1;
  26. static int seed3 = 1;
  27. #define MAXINT (((unsigned)-1)>>1)
  28. #define CRANK(a,b,c,m,s) \
  29. q = s/a; \
  30. s = b*(s-a*q) - c*q; \
  31. if(s<0) s+=m;
  32. int rand()
  33. {
  34. register int q;
  35. CRANK(206, 157, 31, 32363, seed1);
  36. CRANK(217, 146, 45, 31727, seed2);
  37. CRANK(222, 142, 133, 31657, seed3);
  38. return seed1 ^ seed2 ^ seed3;
  39. }
  40. void srand(seed)
  41. unsigned int seed;
  42. {
  43. seed &= MAXINT;
  44. seed1 = seed % 32362 + 1;
  45. seed2 = seed % 31726 + 1;
  46. seed3 = seed % 31656 + 1;
  47. }
  48. #endif