|
Packit |
67cb25 |
/* rng/schrage.c
|
|
Packit |
67cb25 |
* Copyright (C) 2003 Carlo Perassi and Heiko Bauke.
|
|
Packit |
67cb25 |
*
|
|
Packit |
67cb25 |
* This program is free software; you can redistribute it and/or modify
|
|
Packit |
67cb25 |
* it under the terms of the GNU General Public License as published by
|
|
Packit |
67cb25 |
* the Free Software Foundation; either version 3 of the License, or (at
|
|
Packit |
67cb25 |
* your option) any later version.
|
|
Packit |
67cb25 |
*
|
|
Packit |
67cb25 |
* This program is distributed in the hope that it will be useful, but
|
|
Packit |
67cb25 |
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
Packit |
67cb25 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
|
Packit |
67cb25 |
* General Public License for more details.
|
|
Packit |
67cb25 |
*
|
|
Packit |
67cb25 |
* You should have received a copy of the GNU General Public License
|
|
Packit |
67cb25 |
* along with this program; if not, write to the Free Software
|
|
Packit |
67cb25 |
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
|
|
Packit |
67cb25 |
*/
|
|
Packit |
67cb25 |
|
|
Packit |
67cb25 |
static inline unsigned long int
|
|
Packit |
67cb25 |
schrage (unsigned long int a, unsigned long int b, unsigned long int m)
|
|
Packit |
67cb25 |
{
|
|
Packit |
67cb25 |
/* This is a modified version of Schrage's method. It ensures that no
|
|
Packit |
67cb25 |
* overflow or underflow occurs even if a=ceil(sqrt(m)). Usual
|
|
Packit |
67cb25 |
* Schrage's method works only until a=floor(sqrt(m)).
|
|
Packit |
67cb25 |
*/
|
|
Packit |
67cb25 |
unsigned long int q, t;
|
|
Packit |
67cb25 |
if (a == 0UL)
|
|
Packit |
67cb25 |
return 0UL;
|
|
Packit |
67cb25 |
q = m / a;
|
|
Packit |
67cb25 |
t = 2 * m - (m % a) * (b / q);
|
|
Packit |
67cb25 |
if (t >= m)
|
|
Packit |
67cb25 |
t -= m;
|
|
Packit |
67cb25 |
t += a * (b % q);
|
|
Packit |
67cb25 |
return (t >= m) ? (t - m) : t;
|
|
Packit |
67cb25 |
}
|
|
Packit |
67cb25 |
|
|
Packit |
67cb25 |
static inline unsigned long int
|
|
Packit |
67cb25 |
schrage_mult (unsigned long int a, unsigned long int b,
|
|
Packit |
67cb25 |
unsigned long int m,
|
|
Packit |
67cb25 |
unsigned long int sqrtm)
|
|
Packit |
67cb25 |
{
|
|
Packit |
67cb25 |
/* To multiply a and b use Schrage's method 3 times.
|
|
Packit |
67cb25 |
* represent a in base ceil(sqrt(m)) a = a1*ceil(sqrt(m)) + a0
|
|
Packit |
67cb25 |
* a*b = (a1*ceil(sqrt(m)) + a0)*b = a1*ceil(sqrt(m))*b + a0*b
|
|
Packit |
67cb25 |
*/
|
|
Packit |
67cb25 |
unsigned long int t0 = schrage (sqrtm, b, m);
|
|
Packit |
67cb25 |
unsigned long int t1 = schrage (a / sqrtm, t0, m);
|
|
Packit |
67cb25 |
unsigned long int t2 = schrage (a % sqrtm, b, m);
|
|
Packit |
67cb25 |
unsigned long int t = t1 + t2;
|
|
Packit |
67cb25 |
return (t >= m) ? (t - m) : t;
|
|
Packit |
67cb25 |
}
|