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