fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. // Generate a random number not in the range [lo, hi)
  6. int rand_outside(int lo, int hi) {
  7. int rangesize = hi - lo;
  8. int r = rand() % (RAND_MAX - rangesize + 1);
  9. if (r >= lo) r += rangesize;
  10. return r;
  11. }
  12.  
  13. int main(void) {
  14. srand(time(NULL));
  15. int third = RAND_MAX / 3;
  16. int two_thirds = RAND_MAX - third + 1;
  17. int nbottom = 0, ntop = 0, nmiddle = 0;
  18. for (int i = 0; i < 10000; ++i) {
  19. // Get a random number in the bottom third or top third of the possibilities
  20. int r = rand_outside(third, two_thirds);
  21. if (r < third) ++nbottom;
  22. else if (r >= two_thirds) ++ntop;
  23. else ++nmiddle;
  24. }
  25. printf("In range [%10d, %10d]: %4d\n", 0, third - 1, nbottom);
  26. printf("In range [%10d, %10d]: %4d\n", third, two_thirds - 1, nmiddle);
  27. printf("In range [%10d, %10d]: %4d\n", two_thirds, RAND_MAX, ntop);
  28. return 0;
  29. }
  30.  
Success #stdin #stdout 0s 4228KB
stdin
Standard input is empty
stdout
In range [         0,  715827881]: 6628
In range [ 715827882, 1431655765]:    0
In range [1431655766, 2147483647]: 3372