chiark / gitweb /
Karatsuba squaring algorithm.
[catacomb] / mp-arith.c
1 /* -*-c-*-
2  *
3  * $Id: mp-arith.c,v 1.3 1999/12/11 10:57:43 mdw Exp $
4  *
5  * Basic arithmetic on multiprecision integers
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: mp-arith.c,v $
33  * Revision 1.3  1999/12/11 10:57:43  mdw
34  * Karatsuba squaring algorithm.
35  *
36  * Revision 1.2  1999/12/10 23:18:39  mdw
37  * Change interface for suggested destinations.
38  *
39  * Revision 1.1  1999/11/17 18:02:16  mdw
40  * New multiprecision integer arithmetic suite.
41  *
42  */
43
44 /*----- Header files ------------------------------------------------------*/
45
46 #include "mp.h"
47
48 /*----- Macros ------------------------------------------------------------*/
49
50 #define MAX(x, y) ((x) >= (y) ? (x) : (y))
51
52 /*----- Main code ---------------------------------------------------------*/
53
54 /* --- @mp_2c@ --- *
55  *
56  * Arguments:   @mp *a@ = source
57  *
58  * Returns:     Result, @a@ converted to two's complement notation.
59  */
60
61 mp *mp_2c(mp *d, mp *a)
62 {
63   if (!(a->f & MP_NEG))
64     return (MP_COPY(a));
65
66   MP_MODIFY(d, MP_LEN(a));
67   mpx_2c(d->v, d->vl, a->v, a->vl);
68   d->f = a->f & MP_BURN;
69   MP_SHRINK(d);
70   return (d);
71 }
72
73 /* --- @mp_sm@ --- *
74  *
75  * Arguments:   @mp *d@ = destination
76  *              @mp *a@ = source
77  *
78  * Returns:     Result, @a@ converted to the native signed-magnitude
79  *              notation.
80  */
81
82 mp *mp_sm(mp *d, mp *a)
83 {
84   if (!MP_LEN(a) || a->vl[-1] < MPW_MAX / 2)
85     return (MP_COPY(a));
86
87   MP_MODIFY(d, MP_LEN(a));
88   mpx_2c(d->v, d->vl, a->v, a->vl);
89   d->f = (a->f & (MP_BURN | MP_NEG)) ^ MP_NEG;
90   MP_SHRINK(d);
91   return (d);  
92 }
93
94 /* --- @mp_lsl@ --- *
95  *
96  * Arguments:   @mp *d@ = destination
97  *              @mp *a@ = source
98  *              @size_t n@ = number of bits to move
99  *
100  * Returns:     Result, @a@ shifted left by @n@.
101  */
102
103 mp *mp_lsl(mp *d, mp *a, size_t n)
104 {
105   MP_MODIFY(d, MP_LEN(a) + (n + MPW_BITS - 1) / MPW_BITS);
106   mpx_lsl(d->v, d->vl, a->v, a->vl, n);
107   d->f = a->f & (MP_NEG | MP_BURN);
108   MP_SHRINK(d);
109   return (d);
110 }
111
112 /* --- @mp_lsr@ --- *
113  *
114  * Arguments:   @mp *d@ = destination
115  *              @mp *a@ = source
116  *              @size_t n@ = number of bits to move
117  *
118  * Returns:     Result, @a@ shifted left by @n@.
119  */
120
121 mp *mp_lsr(mp *d, mp *a, size_t n)
122 {
123   MP_MODIFY(d, MP_LEN(a));
124   mpx_lsr(d->v, d->vl, a->v, a->vl, n);
125   d->f = a->f & (MP_NEG | MP_BURN);
126   MP_SHRINK(d);
127   return (d);
128 }
129
130 /* --- @mp_cmp@ --- *
131  *
132  * Arguments:   @const mp *a, *b@ = two numbers
133  *
134  * Returns:     Less than, equal to or greater than zero, according to
135  *              whether @a@ is less than, equal to or greater than @b@.
136  */
137
138 int mp_cmp(const mp *a, const mp *b)
139 {
140   if (!((a->f ^ b->f) & MP_NEG))
141     return (mpx_ucmp(a->v, a->vl, b->v, b->vl));
142   else if (a->f & MP_NEG)
143     return (-1);
144   else
145     return (+1);
146 }
147
148 /* --- @mp_add@ --- *
149  *
150  * Arguments:   @mp *d@ = destination
151  *              @mp *a, *b@ = sources
152  *
153  * Returns:     Result, @a@ added to @b@.
154  */
155
156 mp *mp_add(mp *d, mp *a, mp *b)
157 {
158   MP_MODIFY(d, MAX(MP_LEN(a), MP_LEN(b)) + 1);
159   if (!((a->f ^ b->f) & MP_NEG))
160     mpx_uadd(d->v, d->vl, a->v, a->vl, b->v, b->vl);
161   else {
162     if (MPX_UCMP(a->v, a->vl, <, b->v, b->vl)) {
163       mp *t = a; a = b; b = t;
164     }
165     mpx_usub(d->v, d->vl, a->v, a->vl, b->v, b->vl);
166   }
167   d->f = ((a->f | b->f) & MP_BURN) | (a->f & MP_NEG);
168   MP_SHRINK(d);
169   return (d);
170 }
171
172 /* --- @mp_sub@ --- *
173  *
174  * Arguments:   @mp *d@ = destination
175  *              @mp *a, *b@ = sources
176  *
177  * Returns:     Result, @b@ subtracted from @a@.
178  */
179
180 mp *mp_sub(mp *d, mp *a, mp *b)
181 {
182   unsigned sgn = 0;
183   MP_MODIFY(d, MAX(MP_LEN(a), MP_LEN(b)) + 1);
184   if ((a->f ^ b->f) & MP_NEG)
185     mpx_uadd(d->v, d->vl, a->v, a->vl, b->v, b->vl);
186   else {
187     if (MPX_UCMP(a->v, a->vl, <, b->v, b->vl)) {
188       mp *t = a; a = b; b = t;
189       sgn = MP_NEG;
190     }
191     mpx_usub(d->v, d->vl, a->v, a->vl, b->v, b->vl);
192   }
193   d->f = ((a->f | b->f) & MP_BURN) | ((a->f ^ sgn) & MP_NEG);
194   MP_SHRINK(d);
195   return (d);
196 }
197
198 /* --- @mp_mul@ --- *
199  *
200  * Arguments:   @mp *d@ = destination
201  *              @mp *a, *b@ = sources
202  *
203  * Returns:     Result, @a@ multiplied by @b@.
204  */
205
206 mp *mp_mul(mp *d, mp *a, mp *b)
207 {
208   a = MP_COPY(a);
209   b = MP_COPY(b);
210
211   MP_MODIFY(d, MP_LEN(a) + MP_LEN(b));
212   if (MP_LEN(a) <= KARATSUBA_CUTOFF || MP_LEN(b) <= KARATSUBA_CUTOFF)
213     mpx_umul(d->v, d->vl, a->v, a->vl, b->v, b->vl);
214   else {
215     size_t m = MAX(MP_LEN(a), MP_LEN(b)) * 2 + KARATSUBA_SLOP;
216     mpw *s;
217     m += 32;
218     s = MP_ALLOC(m);
219     mpx_kmul(d->v, d->vl, a->v, a->vl, b->v, b->vl, s, s + m);
220     MP_FREE(s);
221   }
222
223   d->f = ((a->f | b->f) & MP_BURN) | ((a->f ^ b->f) & MP_NEG);
224   MP_SHRINK(d);
225   MP_DROP(a);
226   MP_DROP(b);
227   return (d);
228 }
229
230 /* --- @mp_sqr@ --- *
231  *
232  * Arguments:   @mp *d@ = destination
233  *              @mp *a@ = source
234  *
235  * Returns:     Result, @a@ squared.
236  */
237
238 mp *mp_sqr(mp *d, mp *a)
239 {
240   size_t m = MP_LEN(a);
241
242   a = MP_COPY(a);
243   MP_MODIFY(d, 2 * m);
244   if (m > KARATSUBA_CUTOFF) {
245     mpw *s;
246     m = 2 * (m + 1) + 32;
247     s = MP_ALLOC(m);
248     mpx_ksqr(d->v, d->vl, a->v, a->vl, s, s + m);
249     MP_FREE(s);
250   } else 
251     mpx_usqr(d->v, d->vl, a->v, a->vl);
252   d->f = a->f & MP_BURN;
253   MP_SHRINK(d);
254   MP_DROP(a);
255   return (d);
256 }
257
258 /* --- @mp_div@ --- *
259  *
260  * Arguments:   @mp **qq, **rr@ = destination, quotient and remainder
261  *              @mp *a, *b@ = sources
262  *
263  * Use:         Calculates the quotient and remainder when @a@ is divided by
264  *              @b@.  The destinations @*qq@ and @*rr@ must be distinct.
265  *              Either of @qq@ or @rr@ may be null to indicate that the
266  *              result is irrelevant.  (Discarding both results is silly.)
267  *              There is a performance advantage if @a == *rr@.
268  *
269  *              The behaviour when @a@ and @b@ have the same sign is
270  *              straightforward.  When the signs differ, this implementation
271  *              chooses @r@ to have the same sign as @b@, rather than the
272  *              more normal choice that the remainder has the same sign as
273  *              the dividend.  This makes modular arithmetic a little more
274  *              straightforward.
275  */
276
277 void mp_div(mp **qq, mp **rr, mp *a, mp *b)
278  {
279   mp *r = rr ? *rr : MP_NEW;
280   mp *q = qq ? *qq : MP_NEW;
281   mpw *sv, *svl;
282
283   /* --- Set up some temporary workspace --- */
284
285   {
286     size_t rq = MP_LEN(b) + 1;
287     sv = MP_ALLOC(rq);
288     svl = sv + rq;
289   }
290
291   /* --- Set the remainder up right --- *
292    *
293    * Just in case the divisor is larger, be able to cope with this.  It's not
294    * important in @mpx_udiv@, but it is here because of the sign correction.
295    */
296
297   {
298     size_t rq = MP_LEN(a) + 2;
299     if (MP_LEN(b) > rq)
300       rq = MP_LEN(b);
301
302     b = MP_COPY(b);
303     if (r == a) {
304       MP_SPLIT(a);
305       a = r = MP_COPY(a);
306       MP_ENSURE(r, MP_LEN(r) + 2);
307     } else {
308       a = MP_COPY(a);
309       MP_MODIFY(r, MP_LEN(a) + 2);
310       memcpy(r->v, a->v, MPWS(MP_LEN(a)));
311       memset(r->v + MP_LEN(a), 0, MPWS(2));
312     }
313   }
314
315   /* --- Fix up the quotient too --- */
316
317   MP_MODIFY(q, MP_LEN(a));
318
319   /* --- Perform the calculation --- */
320
321   mpx_udiv(q->v, q->vl, r->v, r->vl, b->v, b->vl, sv, svl);
322
323   /* --- Sort out the sign of the results --- *
324    *
325    * If the signs of the arguments differ, and the remainder is nonzero, I
326    * must add one to the absolute value of the quotient and subtract the
327    * remainder from @b@.
328    */
329
330   q->f = ((a->f | b->f) & MP_BURN) | ((a->f ^ b->f) & MP_NEG);
331   if (q->f & MP_NEG) {
332     mpw *v;
333     for (v = r->v; v < r->vl; v++) {
334       if (*v) {
335         MPX_UADDN(q->v, q->vl, 1);
336         mpx_usub(r->v, r->vl, b->v, b->vl, r->v, r->vl);
337         break;
338       }
339     }
340   }
341
342   r->f = ((a->f | b->f) & MP_BURN) | (b->f & MP_NEG);
343
344   /* --- Store the return values --- */
345
346   if (!qq)
347     MP_DROP(q);
348   else {
349     MP_SHRINK(q);
350     *qq = q;
351   }
352
353   if (!rr)
354     MP_DROP(r);
355   else {
356     MP_SHRINK(r);
357     *rr = r;
358   }
359
360   MP_DROP(a);
361   MP_DROP(b);
362   MP_FREE(sv);
363 }
364
365 /*----- Test rig ----------------------------------------------------------*/
366
367 #ifdef TEST_RIG
368
369 static int verify(const char *op, mp *expect, mp *result, mp *a, mp *b)
370 {
371   if (MP_CMP(expect, !=, result)) {
372     fprintf(stderr, "\n*** %s failed", op);
373     fputs("\n*** a      = ", stderr); mp_writefile(a, stderr, 10);
374     fputs("\n*** b      = ", stderr); mp_writefile(b, stderr, 10);
375     fputs("\n*** result = ", stderr); mp_writefile(result, stderr, 10);
376     fputs("\n*** expect = ", stderr); mp_writefile(expect, stderr, 10);
377     fputc('\n', stderr);
378     return (0);
379   }
380   return (1);
381 }
382
383 #define RIG(name, op)                                                   \
384   static int t##name(dstr *v)                                           \
385   {                                                                     \
386     mp *a = *(mp **)v[0].buf;                                           \
387     mpw n = *(int *)v[1].buf;                                           \
388     mp b;                                                               \
389     mp *r = *(mp **)v[2].buf;                                           \
390     mp *c = op(MP_NEW, a, n);                                           \
391     int ok;                                                             \
392     mp_build(&b, &n, &n + 1);                                           \
393     ok = verify(#name, r, c, a, &b);                                    \
394     mp_drop(a); mp_drop(c); mp_drop(r);                                 \
395     assert(mparena_count(MPARENA_GLOBAL) == 0);                         \
396     return (ok);                                                        \
397   }
398
399 RIG(lsl, mp_lsl)
400 RIG(lsr, mp_lsr)
401
402 #undef RIG
403
404 #define RIG(name, op)                                                   \
405   static int t##name(dstr *v)                                           \
406   {                                                                     \
407     mp *a = *(mp **)v[0].buf;                                           \
408     mp *b = *(mp **)v[1].buf;                                           \
409     mp *r = *(mp **)v[2].buf;                                           \
410     mp *c = op(MP_NEW, a, b);                                           \
411     int ok = verify(#name, r, c, a, b);                                 \
412     mp_drop(a); mp_drop(b); mp_drop(c); mp_drop(r);                     \
413     assert(mparena_count(MPARENA_GLOBAL) == 0);                         \
414     return (ok);                                                        \
415   }
416
417 RIG(add, mp_add)
418 RIG(sub, mp_sub)
419 RIG(mul, mp_mul)
420
421 #undef RIG
422
423 static int tdiv(dstr *v)
424 {
425   mp *a = *(mp **)v[0].buf;
426   mp *b = *(mp **)v[1].buf;
427   mp *q = *(mp **)v[2].buf;
428   mp *r = *(mp **)v[3].buf;
429   mp *c = MP_NEW, *d = MP_NEW;
430   int ok = 1;
431   mp_div(&c, &d, a, b);
432   ok &= verify("div(quotient)", q, c, a, b);
433   ok &= verify("div(remainder)", r, d, a, b);
434   mp_drop(a); mp_drop(b); mp_drop(c); mp_drop(d); mp_drop(r); mp_drop(q);
435   assert(mparena_count(MPARENA_GLOBAL) == 0);
436   return (ok);
437 }
438
439 static test_chunk tests[] = {
440   { "lsl", tlsl, { &type_mp, &type_mp, &type_mp, 0 } },
441   { "lsr", tlsr, { &type_mp, &type_mp, &type_mp, 0 } },
442   { "add", tadd, { &type_mp, &type_mp, &type_mp, 0 } },
443   { "sub", tsub, { &type_mp, &type_mp, &type_mp, 0 } },
444   { "mul", tmul, { &type_mp, &type_mp, &type_mp, 0 } },
445   { "div", tdiv, { &type_mp, &type_mp, &type_mp, &type_mp, 0 } },
446   { 0, 0, { 0 } },
447 };
448
449 int main(int argc, char *argv[])
450 {
451   sub_init();
452   test_run(argc, argv, tests, SRCDIR "/tests/mp");
453   return (0);
454 }
455
456 #endif
457
458 /*----- That's all, folks -------------------------------------------------*/