chiark / gitweb /
Version bump.
[catacomb] / mpx-kmul.c
1 /* -*-c-*-
2  *
3  * $Id: mpx-kmul.c,v 1.4 2000/06/17 11:42:11 mdw Exp $
4  *
5  * Karatsuba's multiplication algorithm
6  *
7  * (c) 1999 Straylight/Edgeware
8  */
9
10 /*----- Licensing notice --------------------------------------------------* 
11  *
12  * This file is part of Catacomb.
13  *
14  * Catacomb is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU Library General Public License as
16  * published by the Free Software Foundation; either version 2 of the
17  * License, or (at your option) any later version.
18  * 
19  * Catacomb is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU Library General Public License for more details.
23  * 
24  * You should have received a copy of the GNU Library General Public
25  * License along with Catacomb; if not, write to the Free
26  * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
27  * MA 02111-1307, USA.
28  */
29
30 /*----- Revision history --------------------------------------------------* 
31  *
32  * $Log: mpx-kmul.c,v $
33  * Revision 1.4  2000/06/17 11:42:11  mdw
34  * Moved the Karatsuba macros into a separate file for better sharing.
35  * Fixed some comments.
36  *
37  * Revision 1.3  1999/12/13 15:35:01  mdw
38  * Simplify and improve.
39  *
40  * Revision 1.2  1999/12/11 10:58:02  mdw
41  * Remove tweakable comments.
42  *
43  * Revision 1.1  1999/12/10 23:23:51  mdw
44  * Karatsuba-Ofman multiplication algorithm.
45  *
46  */
47
48 /*----- Header files ------------------------------------------------------*/
49
50 #include <assert.h>
51 #include <stdio.h>
52
53 #include "mpx.h"
54 #include "mpx-kmac.h"
55
56 /*----- Tweakables --------------------------------------------------------*/
57
58 #ifdef TEST_RIG
59 #  undef KARATSUBA_CUTOFF
60 #  define KARATSUBA_CUTOFF 2
61 #endif
62
63 /*----- Main code ---------------------------------------------------------*/
64
65 /* --- @mpx_kmul@ --- *
66  *
67  * Arguments:   @mpw *dv, *dvl@ = pointer to destination buffer
68  *              @const mpw *av, *avl@ = pointer to first argument
69  *              @const mpw *bv, *bvl@ = pointer to second argument
70  *              @mpw *sv, *svl@ = pointer to scratch workspace
71  *
72  * Returns:     ---
73  *
74  * Use:         Multiplies two multiprecision integers using Karatsuba's
75  *              algorithm.  This is rather faster than traditional long
76  *              multiplication (e.g., @mpx_umul@) on large numbers, although
77  *              more expensive on small ones.
78  *
79  *              The destination must be twice as large as the larger
80  *              argument.  The scratch space must be twice as large as the
81  *              larger argument, plus the magic number @KARATSUBA_SLOP@.
82  */
83
84 void mpx_kmul(mpw *dv, mpw *dvl,
85               const mpw *av, const mpw *avl,
86               const mpw *bv, const mpw *bvl,
87               mpw *sv, mpw *svl)
88 {
89   const mpw *avm, *bvm;
90   size_t m;
91
92   /* --- Dispose of easy cases to @mpx_umul@ --- *
93    *
94    * Karatsuba is only a win on large numbers, because of all the
95    * recursiveness and bookkeeping.  The recursive calls make a quick check
96    * to see whether to bottom out to @mpx_umul@ which should help quite a
97    * lot, but sometimes the only way to know is to make sure...
98    */
99
100   MPX_SHRINK(av, avl);
101   MPX_SHRINK(bv, bvl);
102
103   if (avl - av <= KARATSUBA_CUTOFF || bvl - bv <= KARATSUBA_CUTOFF) {
104     mpx_umul(dv, dvl, av, avl, bv, bvl);
105     return;
106   }
107
108   /* --- How the algorithm works --- *
109    *
110    * Let %$A = xb + y$% and %$B = ub + v$%.  Then, simply by expanding,
111    * %$AB = x u b^2 + b(x v + y u) + y v$%.  That's not helped any, because
112    * I've got four multiplications, each four times easier than the one I
113    * started with.  However, note that I can rewrite the coefficient of %$b$%
114    * as %$xv + yu = (x + y)(u + v) - xu - yv$%.  The terms %$xu$% and %$yv$%
115    * I've already calculated, and that leaves only one more multiplication to
116    * do.  So now I have three multiplications, each four times easier, and
117    * that's a win.
118    */
119
120   /* --- First things --- *
121    *
122    * Sort out where to break the factors in half.  I'll choose the midpoint
123    * of the largest one, since this minimizes the amount of work I have to do
124    * most effectively.
125    */
126
127   if (avl - av > bvl - bv) {
128     m = (avl - av + 1) >> 1;
129     avm = av + m;
130     if (bvl - bv > m)
131       bvm = bv + m;
132     else
133       bvm = bvl;
134   } else {
135     m = (bvl - bv + 1) >> 1;
136     bvm = bv + m;
137     if (avl - av > m)
138       avm = av + m;
139     else
140       avm = avl;
141   }
142
143   assert(((void)"Destination too small for Karatsuba multiply",
144           dvl - dv >= 4 * m));
145   assert(((void)"Not enough workspace for Karatsuba multiply",
146           svl - sv >= 4 * m));
147
148   /* --- Sort out the middle term --- */
149
150   {
151     mpw *bsv = sv + m + 1, *ssv = bsv + m + 1;
152     mpw *rdv = dv + m, *rdvl = rdv + 2 * (m + 2);
153
154     UADD2(sv, bsv, av, avm, avm, avl);
155     UADD2(bsv, ssv, bv, bvm, bvm, bvl);
156     if (m > KARATSUBA_CUTOFF)
157       mpx_kmul(rdv, rdvl, sv, bsv, bsv, ssv, ssv, svl);
158     else
159       mpx_umul(rdv, rdvl, sv, bsv, bsv, ssv);
160   }
161
162   /* --- Sort out the other two terms --- */
163
164   {
165     mpw *svm = sv + m, *svn = svm + m, *ssv = svn + 4;
166     mpw *tdv = dv + m;
167     mpw *rdv = tdv + m;
168
169     if (avl == avm || bvl == bvm)
170       MPX_ZERO(rdv + m + 1, dvl);
171     else {
172       if (m > KARATSUBA_CUTOFF)
173         mpx_kmul(sv, ssv, avm, avl, bvm, bvl, ssv, svl);
174       else
175         mpx_umul(sv, ssv, avm, avl, bvm, bvl);
176       MPX_COPY(rdv + m + 1, dvl, svm + 1, svn);
177       UADD(rdv, sv, svm + 1);
178       USUB(tdv, sv, svn);
179     }
180
181     if (m > KARATSUBA_CUTOFF)
182       mpx_kmul(sv, ssv, av, avm, bv, bvm, ssv, svl);
183     else
184       mpx_umul(sv, ssv, av, avm, bv, bvm);
185     MPX_COPY(dv, tdv, sv, svm);
186     USUB(tdv, sv, svn);
187     UADD(tdv, svm, svn);
188   }
189 }
190
191 /*----- Test rig ----------------------------------------------------------*/
192
193 #ifdef TEST_RIG
194
195 #include <mLib/alloc.h>
196 #include <mLib/testrig.h>
197
198 #include "mpscan.h"
199
200 #define ALLOC(v, vl, sz) do {                                           \
201   size_t _sz = (sz);                                                    \
202   mpw *_vv = xmalloc(MPWS(_sz));                                        \
203   mpw *_vvl = _vv + _sz;                                                \
204   (v) = _vv;                                                            \
205   (vl) = _vvl;                                                          \
206 } while (0)
207
208 #define LOAD(v, vl, d) do {                                             \
209   const dstr *_d = (d);                                                 \
210   mpw *_v, *_vl;                                                        \
211   ALLOC(_v, _vl, MPW_RQ(_d->len));                                      \
212   mpx_loadb(_v, _vl, _d->buf, _d->len);                                 \
213   (v) = _v;                                                             \
214   (vl) = _vl;                                                           \
215 } while (0)
216
217 #define MAX(x, y) ((x) > (y) ? (x) : (y))
218
219 static void dumpmp(const char *msg, const mpw *v, const mpw *vl)
220 {
221   fputs(msg, stderr);
222   MPX_SHRINK(v, vl);
223   while (v < vl)
224     fprintf(stderr, " %08lx", (unsigned long)*--vl);
225   fputc('\n', stderr);
226 }
227
228 static int umul(dstr *v)
229 {
230   mpw *a, *al;
231   mpw *b, *bl;
232   mpw *c, *cl;
233   mpw *d, *dl;
234   mpw *s, *sl;
235   size_t m;
236   int ok = 1;
237
238   LOAD(a, al, &v[0]);
239   LOAD(b, bl, &v[1]);
240   LOAD(c, cl, &v[2]);
241   m = MAX(al - a, bl - b) + 1;
242   ALLOC(d, dl, 2 * m);
243   ALLOC(s, sl, 2 * m + 32);
244
245   mpx_kmul(d, dl, a, al, b, bl, s, sl);
246   if (MPX_UCMP(d, dl, !=, c, cl)) {
247     fprintf(stderr, "\n*** umul failed\n");
248     dumpmp("       a", a, al);
249     dumpmp("       b", b, bl);
250     dumpmp("expected", c, cl);
251     dumpmp("  result", d, dl);
252     ok = 0;
253   }
254
255   free(a); free(b); free(c); free(d); free(s);
256   return (ok);
257 }
258
259 static test_chunk defs[] = {
260   { "umul", umul, { &type_hex, &type_hex, &type_hex, 0 } },
261   { 0, 0, { 0 } }
262 };
263
264 int main(int argc, char *argv[])
265 {
266   test_run(argc, argv, defs, SRCDIR"/tests/mpx");
267   return (0);
268 }
269
270 #endif
271
272 /*----- That's all, folks -------------------------------------------------*/