3 * $Id: mp-arith.c,v 1.12 2002/10/09 00:36:03 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.12 2002/10/09 00:36:03 mdw
34 * Fix bounds on workspace for Karatsuba operations.
36 * Revision 1.11 2002/10/06 22:52:50 mdw
37 * Pile of changes for supporting two's complement properly.
39 * Revision 1.10 2001/04/03 19:36:05 mdw
40 * Add some simple bitwise operations so that Perl can use them.
42 * Revision 1.9 2000/10/08 15:48:35 mdw
43 * Rename Karatsuba constants now that we have @gfx_kmul@ too.
45 * Revision 1.8 2000/10/08 12:02:21 mdw
46 * Use @MP_EQ@ instead of @MP_CMP@.
48 * Revision 1.7 2000/06/22 19:02:53 mdw
49 * New function @mp_odd@ to extract powers of two from an integer. This is
50 * common code from the Rabin-Miller test, RSA key recovery and modular
51 * square-root extraction.
53 * Revision 1.6 2000/06/17 11:45:09 mdw
54 * Major memory management overhaul. Added arena support. Use the secure
55 * arena for secret integers. Replace and improve the MP management macros
56 * (e.g., replace MP_MODIFY by MP_DEST).
58 * Revision 1.5 1999/12/22 15:54:41 mdw
59 * Adjust Karatsuba parameters. Calculate destination size better.
61 * Revision 1.4 1999/12/13 15:35:16 mdw
62 * Slightly different rules on memory allocation.
64 * Revision 1.3 1999/12/11 10:57:43 mdw
65 * Karatsuba squaring algorithm.
67 * Revision 1.2 1999/12/10 23:18:39 mdw
68 * Change interface for suggested destinations.
70 * Revision 1.1 1999/11/17 18:02:16 mdw
71 * New multiprecision integer arithmetic suite.
75 /*----- Header files ------------------------------------------------------*/
79 /*----- Macros ------------------------------------------------------------*/
81 #define MAX(x, y) ((x) >= (y) ? (x) : (y))
83 /*----- Main code ---------------------------------------------------------*/
85 /* --- @mp_lsl@, @mp_lsr@ --- *
87 * Arguments: @mp *d@ = destination
89 * @size_t n@ = number of bits to move
91 * Returns: Result, @a@ shifted left or right by @n@.
94 mp *mp_lsl(mp *d, mp *a, size_t n)
96 MP_DEST(d, MP_LEN(a) + (n + MPW_BITS - 1) / MPW_BITS, a->f);
97 mpx_lsl(d->v, d->vl, a->v, a->vl, n);
98 d->f = a->f & (MP_NEG | MP_BURN);
103 mp *mp_lsr(mp *d, mp *a, size_t n)
105 MP_DEST(d, MP_LEN(a), a->f);
106 mpx_lsr(d->v, d->vl, a->v, a->vl, n);
107 d->f = a->f & (MP_NEG | MP_BURN);
112 /* --- @mp_lsl2c@, @mp_lsr2c@ --- *
114 * Arguments: @mp *d@ = destination
116 * @size_t n@ = number of bits to move
118 * Returns: Result, @a@ shifted left or right by @n@. Handles the
119 * pretence of sign-extension for negative numbers.
122 mp *mp_lsl2c(mp *d, mp *a, size_t n)
124 if (!(a->f & MP_NEG))
125 return (mp_lsl(d, a, n));
132 mp *mp_lsr2c(mp *d, mp *a, size_t n)
134 if (!(a->f & MP_NEG))
135 return (mp_lsr(d, a, n));
142 /* --- @mp_testbit@ --- *
144 * Arguments: @mp *x@ = a large integer
145 * @size_t n@ = which bit to test
147 * Returns: Nonzero if the bit is set, zero if not.
150 int mp_testbit(mp *x, size_t n)
153 if (n > MPW_BITS * MP_LEN(x))
157 return ((x->v[o] >> n) & 1);
160 /* --- @mp_testbit2c@ --- *
162 * Arguments: @mp *x@ = a large integer
163 * @size_t n@ = which bit to test
165 * Returns: Nonzero if the bit is set, zero if not. Fakes up two's
166 * complement representation.
169 int mp_testbit2c(mp *x, size_t n)
173 return (mp_testbit(x, n));
174 x = mp_not2c(MP_NEW, x);
175 r = !mp_testbit(x, n);
182 * Arguments: @const mp *a, *b@ = two numbers
184 * Returns: Nonzero if the numbers are equal.
187 int mp_eq(const mp *a, const mp *b) { return (MP_EQ(a, b)); }
189 /* --- @mp_cmp@ --- *
191 * Arguments: @const mp *a, *b@ = two numbers
193 * Returns: Less than, equal to or greater than zero, according to
194 * whether @a@ is less than, equal to or greater than @b@.
197 int mp_cmp(const mp *a, const mp *b)
199 if (!((a->f ^ b->f) & MP_NEG))
200 return (mpx_ucmp(a->v, a->vl, b->v, b->vl));
201 else if (a->f & MP_NEG)
207 /* --- @mp_bitop@ --- *
209 * Arguments: @mp *d@ = destination
210 * @mp *a, *b@ = sources
212 * Returns: The result of the given bitwise operation. These functions
213 * don't handle negative numbers at all sensibly. For that, use
214 * the @...2c@ variants. The functions are named after the
215 * truth tables they generate:
222 #define MP_BITBINOP(string) \
224 mp *mp_bit##string(mp *d, mp *a, mp *b) \
226 MP_DEST(d, MAX(MP_LEN(a), MP_LEN(b)), a->f | b->f); \
227 mpx_bit##string(d->v, d->vl, a->v, a->vl, b->v, b->vl); \
228 d->f = (a->f | b->f) & MP_BURN; \
233 MPX_DOBIN(MP_BITBINOP)
235 /* --- @mp_not@ --- *
237 * Arguments: @mp *d@ = destination
240 * Returns: The bitwise complement of the source.
243 mp *mp_not(mp *d, mp *a)
245 MP_DEST(d, MP_LEN(a), a->f);
246 mpx_not(d->v, d->vl, a->v, a->vl);
247 d->f = a->f & MP_BURN;
252 /* --- @mp_bitop2c@ --- *
254 * Arguments: @mp *d@ = destination
255 * @mp *a, *b@ = sources
257 * Returns: The result of the given bitwise operation. Negative numbers
258 * are treated as two's complement, sign-extended infinitely to
259 * the left. The functions are named after the truth tables
267 /* --- How this actually works --- *
269 * The two arguments are inverted (with a sign-swap) if they're currently
270 * negative. This means that we end up using a different function (one which
271 * reinverts as we go) for the main operation. Also, if the sign would be
272 * negative at the end, we preinvert the output and then invert again with a
275 * Start with: wxyz WXYZ
276 * If @a@ negative: yzwx or YZWX
277 * If @b@ negative: xwzy XWZY
278 * If both negative: zyxw ZYXW
281 #define MP_BIT2CBINOP(n, base, an, bn, abn, p_base, p_an, p_bn, p_abn) \
283 mp *mp_bit##n##2c(mp *d, mp *a, mp *b) \
285 if (!((a->f | b->f) & MP_NEG)) { /* Both positive */ \
286 d = mp_bit##base(d, a, b); \
288 } else if (!(b->f & MP_NEG)) { /* Only @b@ positive */ \
290 d = mp_not2c(d, a); \
291 d = mp_bit##an(d, d, b); \
294 } else if (!(a->f & MP_NEG)) { /* Only @a@ positive */ \
296 d = mp_not2c(d, b); \
297 d = mp_bit##bn(d, a, d); \
300 } else { /* Both negative */ \
301 mp *t = mp_not2c(MP_NEW, a); \
302 mp *d = mp_not2c(d, b); \
303 d = mp_bit##abn(d, t, d); \
310 #define NEG d = mp_not2c(d, d);
312 MP_BIT2CBINOP(0000, 0000, 0000, 0000, 0000, POS, POS, POS, POS)
313 MP_BIT2CBINOP(0001, 0001, 0100, 0010, 0111, POS, POS, POS, NEG)
314 MP_BIT2CBINOP(0010, 0010, 0111, 0001, 0100, POS, NEG, POS, POS)
315 MP_BIT2CBINOP(0011, 0011, 0011, 0011, 0011, POS, NEG, POS, NEG)
316 MP_BIT2CBINOP(0100, 0100, 0001, 0111, 0010, POS, POS, NEG, POS)
317 MP_BIT2CBINOP(0101, 0101, 0101, 0101, 0101, POS, POS, NEG, NEG)
318 MP_BIT2CBINOP(0110, 0110, 0110, 0110, 0110, POS, NEG, NEG, POS)
319 MP_BIT2CBINOP(0111, 0111, 0010, 0100, 0001, POS, NEG, NEG, NEG)
320 MP_BIT2CBINOP(1000, 0111, 0010, 0100, 0001, NEG, POS, POS, POS)
321 MP_BIT2CBINOP(1001, 0110, 0110, 0110, 0110, NEG, POS, POS, NEG)
322 MP_BIT2CBINOP(1010, 0101, 0101, 0101, 0101, NEG, NEG, POS, POS)
323 MP_BIT2CBINOP(1011, 0100, 0001, 0111, 0010, NEG, NEG, POS, NEG)
324 MP_BIT2CBINOP(1100, 0011, 0011, 0011, 0011, NEG, POS, NEG, POS)
325 MP_BIT2CBINOP(1101, 0010, 0111, 0001, 0100, NEG, POS, NEG, NEG)
326 MP_BIT2CBINOP(1110, 0001, 0100, 0010, 0111, NEG, NEG, NEG, POS)
327 MP_BIT2CBINOP(1111, 0000, 0000, 0000, 0000, NEG, NEG, NEG, NEG)
331 /* --- @mp_not2c@ --- *
333 * Arguments: @mp *d@ = destination
336 * Returns: The sign-extended complement of the argument.
339 mp *mp_not2c(mp *d, mp *a)
343 MP_DEST(d, MP_LEN(a) + 1, a->f);
346 MPX_USUBN(d->v, d->vl, 1);
348 MPX_UADDN(d->v, d->vl, 1);
351 mpx_usub(d->v, d->vl, a->v, a->vl, &one, &one + 1);
353 mpx_uadd(d->v, d->vl, a->v, a->vl, &one, &one + 1);
355 d->f = (a->f & (MP_NEG | MP_BURN)) ^ MP_NEG;
360 /* --- @mp_add@ --- *
362 * Arguments: @mp *d@ = destination
363 * @mp *a, *b@ = sources
365 * Returns: Result, @a@ added to @b@.
368 mp *mp_add(mp *d, mp *a, mp *b)
370 MP_DEST(d, MAX(MP_LEN(a), MP_LEN(b)) + 1, a->f | b->f);
371 if (!((a->f ^ b->f) & MP_NEG))
372 mpx_uadd(d->v, d->vl, a->v, a->vl, b->v, b->vl);
374 if (MPX_UCMP(a->v, a->vl, <, b->v, b->vl)) {
375 mp *t = a; a = b; b = t;
377 mpx_usub(d->v, d->vl, a->v, a->vl, b->v, b->vl);
379 d->f = ((a->f | b->f) & MP_BURN) | (a->f & MP_NEG);
384 /* --- @mp_sub@ --- *
386 * Arguments: @mp *d@ = destination
387 * @mp *a, *b@ = sources
389 * Returns: Result, @b@ subtracted from @a@.
392 mp *mp_sub(mp *d, mp *a, mp *b)
395 MP_DEST(d, MAX(MP_LEN(a), MP_LEN(b)) + 1, a->f | b->f);
396 if ((a->f ^ b->f) & MP_NEG)
397 mpx_uadd(d->v, d->vl, a->v, a->vl, b->v, b->vl);
399 if (MPX_UCMP(a->v, a->vl, <, b->v, b->vl)) {
400 mp *t = a; a = b; b = t;
403 mpx_usub(d->v, d->vl, a->v, a->vl, b->v, b->vl);
405 d->f = ((a->f | b->f) & MP_BURN) | ((a->f ^ sgn) & MP_NEG);
410 /* --- @mp_mul@ --- *
412 * Arguments: @mp *d@ = destination
413 * @mp *a, *b@ = sources
415 * Returns: Result, @a@ multiplied by @b@.
418 mp *mp_mul(mp *d, mp *a, mp *b)
423 if (MP_LEN(a) <= MPK_THRESH || MP_LEN(b) <= MPK_THRESH) {
424 MP_DEST(d, MP_LEN(a) + MP_LEN(b), a->f | b->f | MP_UNDEF);
425 mpx_umul(d->v, d->vl, a->v, a->vl, b->v, b->vl);
427 size_t m = MAX(MP_LEN(a), MP_LEN(b));
429 MP_DEST(d, 3 * m, a->f | b->f | MP_UNDEF);
430 s = mpalloc(d->a, 5 * m);
431 mpx_kmul(d->v, d->vl, a->v, a->vl, b->v, b->vl, s, s + 5 * m);
435 d->f = ((a->f | b->f) & MP_BURN) | ((a->f ^ b->f) & MP_NEG);
442 /* --- @mp_sqr@ --- *
444 * Arguments: @mp *d@ = destination
447 * Returns: Result, @a@ squared.
450 mp *mp_sqr(mp *d, mp *a)
452 size_t m = MP_LEN(a);
455 if (m > MPK_THRESH) {
457 MP_DEST(d, 3 * m, a->f | MP_UNDEF);
458 s = mpalloc(d->a, 5 * m);
459 mpx_ksqr(d->v, d->vl, a->v, a->vl, s, s + 5 * m);
462 MP_DEST(d, 2 * m + 2, a->f | MP_UNDEF);
463 mpx_usqr(d->v, d->vl, a->v, a->vl);
465 d->f = a->f & MP_BURN;
471 /* --- @mp_div@ --- *
473 * Arguments: @mp **qq, **rr@ = destination, quotient and remainder
474 * @mp *a, *b@ = sources
476 * Use: Calculates the quotient and remainder when @a@ is divided by
477 * @b@. The destinations @*qq@ and @*rr@ must be distinct.
478 * Either of @qq@ or @rr@ may be null to indicate that the
479 * result is irrelevant. (Discarding both results is silly.)
480 * There is a performance advantage if @a == *rr@.
482 * The behaviour when @a@ and @b@ have the same sign is
483 * straightforward. When the signs differ, this implementation
484 * chooses @r@ to have the same sign as @b@, rather than the
485 * more normal choice that the remainder has the same sign as
486 * the dividend. This makes modular arithmetic a little more
490 void mp_div(mp **qq, mp **rr, mp *a, mp *b)
492 mp *r = rr ? *rr : MP_NEW;
493 mp *q = qq ? *qq : MP_NEW;
496 /* --- Set the remainder up right --- *
498 * Just in case the divisor is larger, be able to cope with this. It's not
499 * important in @mpx_udiv@, but it is here because of the sign correction.
507 MP_DEST(r, MP_LEN(a) + 2, a->f | b->f);
509 /* --- Fix up the quotient too --- */
512 MP_DEST(q, MP_LEN(r), r->f | MP_UNDEF);
515 /* --- Set up some temporary workspace --- */
518 size_t rq = MP_LEN(b) + 1;
519 sv = mpalloc(r->a, rq);
523 /* --- Perform the calculation --- */
525 mpx_udiv(q->v, q->vl, r->v, r->vl, b->v, b->vl, sv, svl);
527 /* --- Sort out the sign of the results --- *
529 * If the signs of the arguments differ, and the remainder is nonzero, I
530 * must add one to the absolute value of the quotient and subtract the
531 * remainder from @b@.
534 q->f = ((r->f | b->f) & MP_BURN) | ((r->f ^ b->f) & MP_NEG);
537 for (v = r->v; v < r->vl; v++) {
539 MPX_UADDN(q->v, q->vl, 1);
540 mpx_usub(r->v, r->vl, b->v, b->vl, r->v, r->vl);
546 r->f = ((r->f | b->f) & MP_BURN) | (b->f & MP_NEG);
548 /* --- Store the return values --- */
568 /* --- @mp_odd@ --- *
570 * Arguments: @mp *d@ = pointer to destination integer
571 * @mp *m@ = pointer to source integer
572 * @size_t *s@ = where to store the power of 2
574 * Returns: An odd integer integer %$t$% such that %$m = 2^s t$%.
576 * Use: Computes a power of two and an odd integer which, when
577 * multiplied, give a specified result. This sort of thing is
578 * useful in number theory quite often.
581 mp *mp_odd(mp *d, mp *m, size_t *s)
588 for (; !*v && v < vl; v++)
595 unsigned z = MPW_BITS / 2;
608 return (mp_lsr(d, m, ss));
611 /*----- Test rig ----------------------------------------------------------*/
615 static int verify(const char *op, mp *expect, mp *result, mp *a, mp *b)
617 if (!MP_EQ(expect, result)) {
618 fprintf(stderr, "\n*** %s failed", op);
619 fputs("\n*** a = ", stderr); mp_writefile(a, stderr, 10);
620 fputs("\n*** b = ", stderr); mp_writefile(b, stderr, 10);
621 fputs("\n*** result = ", stderr); mp_writefile(result, stderr, 10);
622 fputs("\n*** expect = ", stderr); mp_writefile(expect, stderr, 10);
629 #define RIG(name, op) \
630 static int t##name(dstr *v) \
632 mp *a = *(mp **)v[0].buf; \
633 mpw n = *(int *)v[1].buf; \
635 mp *r = *(mp **)v[2].buf; \
636 mp *c = op(MP_NEW, a, n); \
638 mp_build(&b, &n, &n + 1); \
639 ok = verify(#name, r, c, a, &b); \
640 mp_drop(a); mp_drop(c); mp_drop(r); \
641 assert(mparena_count(MPARENA_GLOBAL) == 0); \
652 #define RIG(name, op) \
653 static int t##name(dstr *v) \
655 mp *a = *(mp **)v[0].buf; \
656 mp *b = *(mp **)v[1].buf; \
657 mp *r = *(mp **)v[2].buf; \
658 mp *c = op(MP_NEW, a, b); \
659 int ok = verify(#name, r, c, a, b); \
660 mp_drop(a); mp_drop(b); mp_drop(c); mp_drop(r); \
661 assert(mparena_count(MPARENA_GLOBAL) == 0); \
671 static int tdiv(dstr *v)
673 mp *a = *(mp **)v[0].buf;
674 mp *b = *(mp **)v[1].buf;
675 mp *q = *(mp **)v[2].buf;
676 mp *r = *(mp **)v[3].buf;
677 mp *c = MP_NEW, *d = MP_NEW;
679 mp_div(&c, &d, a, b);
680 ok &= verify("div(quotient)", q, c, a, b);
681 ok &= verify("div(remainder)", r, d, a, b);
682 mp_drop(a); mp_drop(b); mp_drop(c); mp_drop(d); mp_drop(r); mp_drop(q);
683 assert(mparena_count(MPARENA_GLOBAL) == 0);
687 static int tbin(dstr *v)
689 static mp *(*fn[])(mp *, mp *, mp *) = {
690 #define DO(string) mp_bit##string##2c,
696 mp *a = *(mp **)v[1].buf;
697 mp *b = *(mp **)v[2].buf;
698 mp *r = *(mp **)v[3].buf;
701 if (strcmp(v[0].buf, "and") == 0) op = 1;
702 else if (strcmp(v[0].buf, "or") == 0) op = 7;
703 else if (strcmp(v[0].buf, "nand") == 0) op = 14;
704 else if (strcmp(v[0].buf, "nor") == 0) op = 8;
705 else if (strcmp(v[0].buf, "xor") == 0) op = 6;
715 c = fn[op](MP_NEW, a, b);
716 ok = verify(v[0].buf, r, c, a, b);
717 mp_drop(a); mp_drop(b); mp_drop(r); mp_drop(c);
718 assert(mparena_count(MPARENA_GLOBAL) == 0);
722 static int todd(dstr *v)
724 mp *a = *(mp **)v[0].buf;
725 size_t rs = *(uint32 *)v[1].buf;
726 mp *rt = *(mp **)v[2].buf;
730 t = mp_odd(MP_NEW, a, &s);
731 if (s != rs || !MP_EQ(t, rt)) {
733 fprintf(stderr, "\n*** odd failed");
734 fputs("\n*** a = ", stderr); mp_writefile(a, stderr, 10);
735 fprintf(stderr, "\n*** s = %lu", (unsigned long)s);
736 fputs("\n*** t = ", stderr); mp_writefile(t, stderr, 10);
737 fprintf(stderr, "\n*** rs = %lu", (unsigned long)rs);
738 fputs("\n*** rt = ", stderr); mp_writefile(rt, stderr, 10);
747 static test_chunk tests[] = {
748 { "lsl", tlsl, { &type_mp, &type_int, &type_mp, 0 } },
749 { "lsr", tlsr, { &type_mp, &type_int, &type_mp, 0 } },
750 { "lsl2c", tlsl2c, { &type_mp, &type_int, &type_mp, 0 } },
751 { "lsr2c", tlsr2c, { &type_mp, &type_int, &type_mp, 0 } },
752 { "add", tadd, { &type_mp, &type_mp, &type_mp, 0 } },
753 { "sub", tsub, { &type_mp, &type_mp, &type_mp, 0 } },
754 { "mul", tmul, { &type_mp, &type_mp, &type_mp, 0 } },
755 { "div", tdiv, { &type_mp, &type_mp, &type_mp, &type_mp, 0 } },
756 { "bin2c", tbin, { &type_string, &type_mp, &type_mp, &type_mp, 0 } },
757 { "odd", todd, { &type_mp, &type_uint32, &type_mp, 0 } },
761 int main(int argc, char *argv[])
764 test_run(argc, argv, tests, SRCDIR "/tests/mp");
770 /*----- That's all, folks -------------------------------------------------*/