fork download
  1. #include <stdio.h>
  2. #include <stdint.h>
  3.  
  4. typedef struct {
  5. uint32_t low;
  6. uint32_t high;
  7. } twoint;
  8.  
  9. typedef struct {
  10. twoint a;
  11. twoint b;
  12. } twostate;
  13.  
  14. uint64_t simple_lcg(uint64_t a, uint64_t c, uint64_t m, uint64_t x) {
  15. return ((a * x) + c) % m;
  16. }
  17.  
  18. uint64_t twoint_to_long(twoint num) {
  19. void* something = (void*)&num;
  20. uint64_t* result = (uint64_t*)something;
  21. return *result;
  22. }
  23.  
  24. twoint long_to_twoint(uint64_t num) {
  25. void* something = (void*)&num;
  26. twoint* result = (twoint*)something;
  27. return *result;
  28. }
  29.  
  30. uint64_t badRand(twostate* state) {
  31. twoint num = { state->a.low, state->b.low };
  32. return twoint_to_long(num);
  33. }
  34.  
  35. uint64_t goodRand(twostate* state) {
  36. twoint num = { state->a.high, state->b.high };
  37. return twoint_to_long(num);
  38. }
  39.  
  40. void lcg(twostate* state) {
  41. #define ELCG(x) simple_lcg(0xABAD1DEA, 0xDEADBEEF, UINT64_MAX, x)
  42. uint64_t na = ELCG(twoint_to_long(state->a));
  43. uint64_t nb = ELCG(twoint_to_long(state->b));
  44.  
  45. state->a = long_to_twoint(na);
  46. state->b = long_to_twoint(nb);
  47. }
  48.  
  49. int main(int argc, char *argv[])
  50. {
  51. twoint a = { 1, 2 };
  52. twoint b = { 3, 4 };
  53. twostate state = { a, b };
  54.  
  55. for(int i = 0; i < 10; i++) {
  56. lcg(&state);
  57. printf("[%d]\n", i + 1);
  58. printf("Good random, use it: %llu \n", goodRand(&state));
  59. printf("Bad random, don't use it: %llu \n", badRand(&state));
  60. }
  61. return 0;
  62. }
  63.  
Success #stdin #stdout 0s 2008KB
stdin
Standard input is empty
stdout
[1]
Good random, use it: 12588818431901055957 
Bad random, don't use it: 16263932762948033753 
[2]
Good random, use it: 2720803787676259017 
Bad random, don't use it: 17143767895757894217 
[3]
Good random, use it: 12088632693136085066 
Bad random, don't use it: 14407287308702513833 
[4]
Good random, use it: 8217024325019233430 
Bad random, don't use it: 18211897777719673449 
[5]
Good random, use it: 12656807529656163924 
Bad random, don't use it: 14390778897813526505 
[6]
Good random, use it: 5545660948545904246 
Bad random, don't use it: 5636979963685338857 
[7]
Good random, use it: 6623761171995285576 
Bad random, don't use it: 14114388887445513449 
[8]
Good random, use it: 1763128157691682133 
Bad random, don't use it: 2473499746185830633 
[9]
Good random, use it: 2959415399114682595 
Bad random, don't use it: 8289452261783025897 
[10]
Good random, use it: 1181416572144120035 
Bad random, don't use it: 9640219887008884969