3 * $Id: mp-arith.c,v 1.7 2000/06/22 19:02:53 mdw Exp $
5 * Basic arithmetic on multiprecision integers
7 * (c) 1999 Straylight/Edgeware
10 /*----- Licensing notice --------------------------------------------------*
12 * This file is part of Catacomb.
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.
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.
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,
30 /*----- Revision history --------------------------------------------------*
32 * $Log: mp-arith.c,v $
33 * Revision 1.7 2000/06/22 19:02:53 mdw
34 * New function @mp_odd@ to extract powers of two from an integer. This is
35 * common code from the Rabin-Miller test, RSA key recovery and modular
36 * square-root extraction.
38 * Revision 1.6 2000/06/17 11:45:09 mdw
39 * Major memory management overhaul. Added arena support. Use the secure
40 * arena for secret integers. Replace and improve the MP management macros
41 * (e.g., replace MP_MODIFY by MP_DEST).
43 * Revision 1.5 1999/12/22 15:54:41 mdw
44 * Adjust Karatsuba parameters. Calculate destination size better.
46 * Revision 1.4 1999/12/13 15:35:16 mdw
47 * Slightly different rules on memory allocation.
49 * Revision 1.3 1999/12/11 10:57:43 mdw
50 * Karatsuba squaring algorithm.
52 * Revision 1.2 1999/12/10 23:18:39 mdw
53 * Change interface for suggested destinations.
55 * Revision 1.1 1999/11/17 18:02:16 mdw
56 * New multiprecision integer arithmetic suite.
60 /*----- Header files ------------------------------------------------------*/
64 /*----- Macros ------------------------------------------------------------*/
66 #define MAX(x, y) ((x) >= (y) ? (x) : (y))
68 /*----- Main code ---------------------------------------------------------*/
72 * Arguments: @mp *a@ = source
74 * Returns: Result, @a@ converted to two's complement notation.
77 mp *mp_2c(mp *d, mp *a)
82 MP_DEST(d, MP_LEN(a), a->f);
83 mpx_2c(d->v, d->vl, a->v, a->vl);
84 d->f = a->f & MP_BURN;
91 * Arguments: @mp *d@ = destination
94 * Returns: Result, @a@ converted to the native signed-magnitude
98 mp *mp_sm(mp *d, mp *a)
100 if (!MP_LEN(a) || a->vl[-1] < MPW_MAX / 2)
103 MP_DEST(d, MP_LEN(a), a->f);
104 mpx_2c(d->v, d->vl, a->v, a->vl);
105 d->f = (a->f & (MP_BURN | MP_NEG)) ^ MP_NEG;
110 /* --- @mp_lsl@ --- *
112 * Arguments: @mp *d@ = destination
114 * @size_t n@ = number of bits to move
116 * Returns: Result, @a@ shifted left by @n@.
119 mp *mp_lsl(mp *d, mp *a, size_t n)
121 MP_DEST(d, MP_LEN(a) + (n + MPW_BITS - 1) / MPW_BITS, a->f);
122 mpx_lsl(d->v, d->vl, a->v, a->vl, n);
123 d->f = a->f & (MP_NEG | MP_BURN);
128 /* --- @mp_lsr@ --- *
130 * Arguments: @mp *d@ = destination
132 * @size_t n@ = number of bits to move
134 * Returns: Result, @a@ shifted left by @n@.
137 mp *mp_lsr(mp *d, mp *a, size_t n)
139 MP_DEST(d, MP_LEN(a), a->f);
140 mpx_lsr(d->v, d->vl, a->v, a->vl, n);
141 d->f = a->f & (MP_NEG | MP_BURN);
146 /* --- @mp_cmp@ --- *
148 * Arguments: @const mp *a, *b@ = two numbers
150 * Returns: Less than, equal to or greater than zero, according to
151 * whether @a@ is less than, equal to or greater than @b@.
154 int mp_cmp(const mp *a, const mp *b)
156 if (!((a->f ^ b->f) & MP_NEG))
157 return (mpx_ucmp(a->v, a->vl, b->v, b->vl));
158 else if (a->f & MP_NEG)
164 /* --- @mp_add@ --- *
166 * Arguments: @mp *d@ = destination
167 * @mp *a, *b@ = sources
169 * Returns: Result, @a@ added to @b@.
172 mp *mp_add(mp *d, mp *a, mp *b)
174 MP_DEST(d, MAX(MP_LEN(a), MP_LEN(b)) + 1, a->f | b->f);
175 if (!((a->f ^ b->f) & MP_NEG))
176 mpx_uadd(d->v, d->vl, a->v, a->vl, b->v, b->vl);
178 if (MPX_UCMP(a->v, a->vl, <, b->v, b->vl)) {
179 mp *t = a; a = b; b = t;
181 mpx_usub(d->v, d->vl, a->v, a->vl, b->v, b->vl);
183 d->f = ((a->f | b->f) & MP_BURN) | (a->f & MP_NEG);
188 /* --- @mp_sub@ --- *
190 * Arguments: @mp *d@ = destination
191 * @mp *a, *b@ = sources
193 * Returns: Result, @b@ subtracted from @a@.
196 mp *mp_sub(mp *d, mp *a, mp *b)
199 MP_DEST(d, MAX(MP_LEN(a), MP_LEN(b)) + 1, a->f | b->f);
200 if ((a->f ^ b->f) & MP_NEG)
201 mpx_uadd(d->v, d->vl, a->v, a->vl, b->v, b->vl);
203 if (MPX_UCMP(a->v, a->vl, <, b->v, b->vl)) {
204 mp *t = a; a = b; b = t;
207 mpx_usub(d->v, d->vl, a->v, a->vl, b->v, b->vl);
209 d->f = ((a->f | b->f) & MP_BURN) | ((a->f ^ sgn) & MP_NEG);
214 /* --- @mp_mul@ --- *
216 * Arguments: @mp *d@ = destination
217 * @mp *a, *b@ = sources
219 * Returns: Result, @a@ multiplied by @b@.
222 mp *mp_mul(mp *d, mp *a, mp *b)
227 if (MP_LEN(a) <= KARATSUBA_CUTOFF || MP_LEN(b) <= KARATSUBA_CUTOFF) {
228 MP_DEST(d, MP_LEN(a) + MP_LEN(b), a->f | b->f | MP_UNDEF);
229 mpx_umul(d->v, d->vl, a->v, a->vl, b->v, b->vl);
231 size_t m = 2 * MAX(MP_LEN(a), MP_LEN(b)) + 2;
233 MP_DEST(d, m, a->f | b->f | MP_UNDEF);
235 s = mpalloc(d->a, m);
236 mpx_kmul(d->v, d->vl, a->v, a->vl, b->v, b->vl, s, s + m);
240 d->f = ((a->f | b->f) & MP_BURN) | ((a->f ^ b->f) & MP_NEG);
247 /* --- @mp_sqr@ --- *
249 * Arguments: @mp *d@ = destination
252 * Returns: Result, @a@ squared.
255 mp *mp_sqr(mp *d, mp *a)
257 size_t m = MP_LEN(a);
260 MP_DEST(d, 2 * m + 2, a->f | MP_UNDEF);
261 if (m > KARATSUBA_CUTOFF) {
263 m = 2 * (m + 1) + KARATSUBA_SLOP;
264 s = mpalloc(d->a, m);
265 mpx_ksqr(d->v, d->vl, a->v, a->vl, s, s + m);
268 mpx_usqr(d->v, d->vl, a->v, a->vl);
269 d->f = a->f & MP_BURN;
275 /* --- @mp_div@ --- *
277 * Arguments: @mp **qq, **rr@ = destination, quotient and remainder
278 * @mp *a, *b@ = sources
280 * Use: Calculates the quotient and remainder when @a@ is divided by
281 * @b@. The destinations @*qq@ and @*rr@ must be distinct.
282 * Either of @qq@ or @rr@ may be null to indicate that the
283 * result is irrelevant. (Discarding both results is silly.)
284 * There is a performance advantage if @a == *rr@.
286 * The behaviour when @a@ and @b@ have the same sign is
287 * straightforward. When the signs differ, this implementation
288 * chooses @r@ to have the same sign as @b@, rather than the
289 * more normal choice that the remainder has the same sign as
290 * the dividend. This makes modular arithmetic a little more
294 void mp_div(mp **qq, mp **rr, mp *a, mp *b)
296 mp *r = rr ? *rr : MP_NEW;
297 mp *q = qq ? *qq : MP_NEW;
300 /* --- Set the remainder up right --- *
302 * Just in case the divisor is larger, be able to cope with this. It's not
303 * important in @mpx_udiv@, but it is here because of the sign correction.
311 MP_DEST(r, MP_LEN(a) + 2, a->f | b->f);
313 /* --- Fix up the quotient too --- */
316 MP_DEST(q, MP_LEN(r), r->f | MP_UNDEF);
319 /* --- Set up some temporary workspace --- */
322 size_t rq = MP_LEN(b) + 1;
323 sv = mpalloc(r->a, rq);
327 /* --- Perform the calculation --- */
329 mpx_udiv(q->v, q->vl, r->v, r->vl, b->v, b->vl, sv, svl);
331 /* --- Sort out the sign of the results --- *
333 * If the signs of the arguments differ, and the remainder is nonzero, I
334 * must add one to the absolute value of the quotient and subtract the
335 * remainder from @b@.
338 q->f = ((r->f | b->f) & MP_BURN) | ((r->f ^ b->f) & MP_NEG);
341 for (v = r->v; v < r->vl; v++) {
343 MPX_UADDN(q->v, q->vl, 1);
344 mpx_usub(r->v, r->vl, b->v, b->vl, r->v, r->vl);
350 r->f = ((r->f | b->f) & MP_BURN) | (b->f & MP_NEG);
352 /* --- Store the return values --- */
372 /* --- @mp_odd@ --- *
374 * Arguments: @mp *d@ = pointer to destination integer
375 * @mp *m@ = pointer to source integer
376 * @size_t *s@ = where to store the power of 2
378 * Returns: An odd integer integer %$t$% such that %$m = 2^s t$%.
380 * Use: Computes a power of two and an odd integer which, when
381 * multiplied, give a specified result. This sort of thing is
382 * useful in number theory quite often.
385 mp *mp_odd(mp *d, mp *m, size_t *s)
392 for (; !*v && v < vl; v++)
399 unsigned z = MPW_BITS / 2;
412 return (mp_lsr(d, m, ss));
415 /*----- Test rig ----------------------------------------------------------*/
419 static int verify(const char *op, mp *expect, mp *result, mp *a, mp *b)
421 if (MP_CMP(expect, !=, result)) {
422 fprintf(stderr, "\n*** %s failed", op);
423 fputs("\n*** a = ", stderr); mp_writefile(a, stderr, 10);
424 fputs("\n*** b = ", stderr); mp_writefile(b, stderr, 10);
425 fputs("\n*** result = ", stderr); mp_writefile(result, stderr, 10);
426 fputs("\n*** expect = ", stderr); mp_writefile(expect, stderr, 10);
433 #define RIG(name, op) \
434 static int t##name(dstr *v) \
436 mp *a = *(mp **)v[0].buf; \
437 mpw n = *(int *)v[1].buf; \
439 mp *r = *(mp **)v[2].buf; \
440 mp *c = op(MP_NEW, a, n); \
442 mp_build(&b, &n, &n + 1); \
443 ok = verify(#name, r, c, a, &b); \
444 mp_drop(a); mp_drop(c); mp_drop(r); \
445 assert(mparena_count(MPARENA_GLOBAL) == 0); \
454 #define RIG(name, op) \
455 static int t##name(dstr *v) \
457 mp *a = *(mp **)v[0].buf; \
458 mp *b = *(mp **)v[1].buf; \
459 mp *r = *(mp **)v[2].buf; \
460 mp *c = op(MP_NEW, a, b); \
461 int ok = verify(#name, r, c, a, b); \
462 mp_drop(a); mp_drop(b); mp_drop(c); mp_drop(r); \
463 assert(mparena_count(MPARENA_GLOBAL) == 0); \
473 static int tdiv(dstr *v)
475 mp *a = *(mp **)v[0].buf;
476 mp *b = *(mp **)v[1].buf;
477 mp *q = *(mp **)v[2].buf;
478 mp *r = *(mp **)v[3].buf;
479 mp *c = MP_NEW, *d = MP_NEW;
481 mp_div(&c, &d, a, b);
482 ok &= verify("div(quotient)", q, c, a, b);
483 ok &= verify("div(remainder)", r, d, a, b);
484 mp_drop(a); mp_drop(b); mp_drop(c); mp_drop(d); mp_drop(r); mp_drop(q);
485 assert(mparena_count(MPARENA_GLOBAL) == 0);
489 static int todd(dstr *v)
491 mp *a = *(mp **)v[0].buf;
492 size_t rs = *(uint32 *)v[1].buf;
493 mp *rt = *(mp **)v[2].buf;
497 t = mp_odd(MP_NEW, a, &s);
498 if (s != rs || MP_CMP(t, !=, rt)) {
500 fprintf(stderr, "\n*** odd failed");
501 fputs("\n*** a = ", stderr); mp_writefile(a, stderr, 10);
502 fprintf(stderr, "\n*** s = %lu", (unsigned long)s);
503 fputs("\n*** t = ", stderr); mp_writefile(t, stderr, 10);
504 fprintf(stderr, "\n*** rs = %lu", (unsigned long)rs);
505 fputs("\n*** rt = ", stderr); mp_writefile(rt, stderr, 10);
514 static test_chunk tests[] = {
515 { "lsl", tlsl, { &type_mp, &type_mp, &type_mp, 0 } },
516 { "lsr", tlsr, { &type_mp, &type_mp, &type_mp, 0 } },
517 { "add", tadd, { &type_mp, &type_mp, &type_mp, 0 } },
518 { "sub", tsub, { &type_mp, &type_mp, &type_mp, 0 } },
519 { "mul", tmul, { &type_mp, &type_mp, &type_mp, 0 } },
520 { "div", tdiv, { &type_mp, &type_mp, &type_mp, &type_mp, 0 } },
521 { "odd", todd, { &type_mp, &type_uint32, &type_mp, 0 } },
525 int main(int argc, char *argv[])
528 test_run(argc, argv, tests, SRCDIR "/tests/mp");
534 /*----- That's all, folks -------------------------------------------------*/