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