gsl_rng__schrage.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /* rng/schrage.c
  2. * Copyright (C) 2003 Carlo Perassi and Heiko Bauke.
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or (at
  7. * your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  17. */
  18. static inline unsigned long int
  19. schrage (unsigned long int a, unsigned long int b, unsigned long int m)
  20. {
  21. /* This is a modified version of Schrage's method. It ensures that no
  22. * overflow or underflow occurs even if a=ceil(sqrt(m)). Usual
  23. * Schrage's method works only until a=floor(sqrt(m)).
  24. */
  25. unsigned long int q, t;
  26. if (a == 0UL)
  27. return 0UL;
  28. q = m / a;
  29. t = 2 * m - (m % a) * (b / q);
  30. if (t >= m)
  31. t -= m;
  32. t += a * (b % q);
  33. return (t >= m) ? (t - m) : t;
  34. }
  35. static inline unsigned long int
  36. schrage_mult (unsigned long int a, unsigned long int b,
  37. unsigned long int m,
  38. unsigned long int sqrtm)
  39. {
  40. /* To multiply a and b use Schrage's method 3 times.
  41. * represent a in base ceil(sqrt(m)) a = a1*ceil(sqrt(m)) + a0
  42. * a*b = (a1*ceil(sqrt(m)) + a0)*b = a1*ceil(sqrt(m))*b + a0*b
  43. */
  44. unsigned long int t0 = schrage (sqrtm, b, m);
  45. unsigned long int t1 = schrage (a / sqrtm, t0, m);
  46. unsigned long int t2 = schrage (a % sqrtm, b, m);
  47. unsigned long int t = t1 + t2;
  48. return (t >= m) ? (t - m) : t;
  49. }