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