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