ntruerand.c 371 B

1234567891011121314151617181920212223
  1. #include <u.h>
  2. #include <libc.h>
  3. ulong
  4. ntruerand(ulong n)
  5. {
  6. ulong m, r;
  7. /*
  8. * set m to the one less than the maximum multiple of n <= 2^32,
  9. * so we want a random number <= m.
  10. */
  11. if(n > (1UL<<31))
  12. m = n-1;
  13. else
  14. /* 2^32 - 2^32%n - 1 = (2^32 - 1) - (2*(2^31%n))%n */
  15. m = 0xFFFFFFFFUL - (2*((1UL<<31)%n))%n;
  16. while((r = truerand()) > m)
  17. ;
  18. return r%n;
  19. }