3 * $Id: mp-arith.c,v 1.10 2001/04/03 19:36:05 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.10 2001/04/03 19:36:05 mdw
34 * Add some simple bitwise operations so that Perl can use them.
36 * Revision 1.9 2000/10/08 15:48:35 mdw
37 * Rename Karatsuba constants now that we have @gfx_kmul@ too.
39 * Revision 1.8 2000/10/08 12:02:21 mdw
40 * Use @MP_EQ@ instead of @MP_CMP@.
42 * Revision 1.7 2000/06/22 19:02:53 mdw
43 * New function @mp_odd@ to extract powers of two from an integer. This is
44 * common code from the Rabin-Miller test, RSA key recovery and modular
45 * square-root extraction.
47 * Revision 1.6 2000/06/17 11:45:09 mdw
48 * Major memory management overhaul. Added arena support. Use the secure
49 * arena for secret integers. Replace and improve the MP management macros
50 * (e.g., replace MP_MODIFY by MP_DEST).
52 * Revision 1.5 1999/12/22 15:54:41 mdw
53 * Adjust Karatsuba parameters. Calculate destination size better.
55 * Revision 1.4 1999/12/13 15:35:16 mdw
56 * Slightly different rules on memory allocation.
58 * Revision 1.3 1999/12/11 10:57:43 mdw
59 * Karatsuba squaring algorithm.
61 * Revision 1.2 1999/12/10 23:18:39 mdw
62 * Change interface for suggested destinations.
64 * Revision 1.1 1999/11/17 18:02:16 mdw
65 * New multiprecision integer arithmetic suite.
69 /*----- Header files ------------------------------------------------------*/
73 /*----- Macros ------------------------------------------------------------*/
75 #define MAX(x, y) ((x) >= (y) ? (x) : (y))
77 /*----- Main code ---------------------------------------------------------*/
81 * Arguments: @mp *a@ = source
83 * Returns: Result, @a@ converted to two's complement notation.
86 mp *mp_2c(mp *d, mp *a)
91 MP_DEST(d, MP_LEN(a), a->f);
92 mpx_2c(d->v, d->vl, a->v, a->vl);
93 d->f = a->f & MP_BURN;
100 * Arguments: @mp *d@ = destination
103 * Returns: Result, @a@ converted to the native signed-magnitude
107 mp *mp_sm(mp *d, mp *a)
109 if (!MP_LEN(a) || a->vl[-1] < MPW_MAX / 2)
112 MP_DEST(d, MP_LEN(a), a->f);
113 mpx_2c(d->v, d->vl, a->v, a->vl);
114 d->f = (a->f & (MP_BURN | MP_NEG)) ^ MP_NEG;
119 /* --- @mp_lsl@ --- *
121 * Arguments: @mp *d@ = destination
123 * @size_t n@ = number of bits to move
125 * Returns: Result, @a@ shifted left by @n@.
128 mp *mp_lsl(mp *d, mp *a, size_t n)
130 MP_DEST(d, MP_LEN(a) + (n + MPW_BITS - 1) / MPW_BITS, a->f);
131 mpx_lsl(d->v, d->vl, a->v, a->vl, n);
132 d->f = a->f & (MP_NEG | MP_BURN);
137 /* --- @mp_lsr@ --- *
139 * Arguments: @mp *d@ = destination
141 * @size_t n@ = number of bits to move
143 * Returns: Result, @a@ shifted left by @n@.
146 mp *mp_lsr(mp *d, mp *a, size_t n)
148 MP_DEST(d, MP_LEN(a), a->f);
149 mpx_lsr(d->v, d->vl, a->v, a->vl, n);
150 d->f = a->f & (MP_NEG | MP_BURN);
157 * Arguments: @const mp *a, *b@ = two numbers
159 * Returns: Nonzero if the numbers are equal.
162 int mp_eq(const mp *a, const mp *b) { return (MP_EQ(a, b)); }
164 /* --- @mp_cmp@ --- *
166 * Arguments: @const mp *a, *b@ = two numbers
168 * Returns: Less than, equal to or greater than zero, according to
169 * whether @a@ is less than, equal to or greater than @b@.
172 int mp_cmp(const mp *a, const mp *b)
174 if (!((a->f ^ b->f) & MP_NEG))
175 return (mpx_ucmp(a->v, a->vl, b->v, b->vl));
176 else if (a->f & MP_NEG)
182 /* --- @mpx_and@, @mpx_or@, @mpx_xor@, @mpx_not@ --- *
184 * Arguments: @mp *d@ = destination
185 * @mp *a, *b@ = sources
187 * Returns: The result of the obvious bitwise operation.
190 #define MP_BITBINOP(name) \
192 mp *mp_##name(mp *d, mp *a, mp *b) \
194 MP_DEST(d, MAX(MP_LEN(a), MP_LEN(b)), a->f | b->f); \
195 mpx_##name(d->v, d->vl, a->v, a->vl, b->v, b->vl); \
196 d->f = (a->f | b->f) & MP_BURN; \
205 mp *mp_not(mp *d, mp *a)
207 MP_DEST(d, MP_LEN(a), a->f);
208 mpx_not(d->v, d->vl, a->v, a->vl);
209 d->f = a->f & MP_BURN;
214 /* --- @mp_add@ --- *
216 * Arguments: @mp *d@ = destination
217 * @mp *a, *b@ = sources
219 * Returns: Result, @a@ added to @b@.
222 mp *mp_add(mp *d, mp *a, mp *b)
224 MP_DEST(d, MAX(MP_LEN(a), MP_LEN(b)) + 1, a->f | b->f);
225 if (!((a->f ^ b->f) & MP_NEG))
226 mpx_uadd(d->v, d->vl, a->v, a->vl, b->v, b->vl);
228 if (MPX_UCMP(a->v, a->vl, <, b->v, b->vl)) {
229 mp *t = a; a = b; b = t;
231 mpx_usub(d->v, d->vl, a->v, a->vl, b->v, b->vl);
233 d->f = ((a->f | b->f) & MP_BURN) | (a->f & MP_NEG);
238 /* --- @mp_sub@ --- *
240 * Arguments: @mp *d@ = destination
241 * @mp *a, *b@ = sources
243 * Returns: Result, @b@ subtracted from @a@.
246 mp *mp_sub(mp *d, mp *a, mp *b)
249 MP_DEST(d, MAX(MP_LEN(a), MP_LEN(b)) + 1, a->f | b->f);
250 if ((a->f ^ b->f) & MP_NEG)
251 mpx_uadd(d->v, d->vl, a->v, a->vl, b->v, b->vl);
253 if (MPX_UCMP(a->v, a->vl, <, b->v, b->vl)) {
254 mp *t = a; a = b; b = t;
257 mpx_usub(d->v, d->vl, a->v, a->vl, b->v, b->vl);
259 d->f = ((a->f | b->f) & MP_BURN) | ((a->f ^ sgn) & MP_NEG);
264 /* --- @mp_mul@ --- *
266 * Arguments: @mp *d@ = destination
267 * @mp *a, *b@ = sources
269 * Returns: Result, @a@ multiplied by @b@.
272 mp *mp_mul(mp *d, mp *a, mp *b)
277 if (MP_LEN(a) <= MPK_THRESH || MP_LEN(b) <= MPK_THRESH) {
278 MP_DEST(d, MP_LEN(a) + MP_LEN(b), a->f | b->f | MP_UNDEF);
279 mpx_umul(d->v, d->vl, a->v, a->vl, b->v, b->vl);
281 size_t m = 2 * MAX(MP_LEN(a), MP_LEN(b)) + 2;
283 MP_DEST(d, m, a->f | b->f | MP_UNDEF);
285 s = mpalloc(d->a, m);
286 mpx_kmul(d->v, d->vl, a->v, a->vl, b->v, b->vl, s, s + m);
290 d->f = ((a->f | b->f) & MP_BURN) | ((a->f ^ b->f) & MP_NEG);
297 /* --- @mp_sqr@ --- *
299 * Arguments: @mp *d@ = destination
302 * Returns: Result, @a@ squared.
305 mp *mp_sqr(mp *d, mp *a)
307 size_t m = MP_LEN(a);
310 MP_DEST(d, 2 * m + 2, a->f | MP_UNDEF);
311 if (m > MPK_THRESH) {
313 m = 2 * (m + 1) + MPK_SLOP;
314 s = mpalloc(d->a, m);
315 mpx_ksqr(d->v, d->vl, a->v, a->vl, s, s + m);
318 mpx_usqr(d->v, d->vl, a->v, a->vl);
319 d->f = a->f & MP_BURN;
325 /* --- @mp_div@ --- *
327 * Arguments: @mp **qq, **rr@ = destination, quotient and remainder
328 * @mp *a, *b@ = sources
330 * Use: Calculates the quotient and remainder when @a@ is divided by
331 * @b@. The destinations @*qq@ and @*rr@ must be distinct.
332 * Either of @qq@ or @rr@ may be null to indicate that the
333 * result is irrelevant. (Discarding both results is silly.)
334 * There is a performance advantage if @a == *rr@.
336 * The behaviour when @a@ and @b@ have the same sign is
337 * straightforward. When the signs differ, this implementation
338 * chooses @r@ to have the same sign as @b@, rather than the
339 * more normal choice that the remainder has the same sign as
340 * the dividend. This makes modular arithmetic a little more
344 void mp_div(mp **qq, mp **rr, mp *a, mp *b)
346 mp *r = rr ? *rr : MP_NEW;
347 mp *q = qq ? *qq : MP_NEW;
350 /* --- Set the remainder up right --- *
352 * Just in case the divisor is larger, be able to cope with this. It's not
353 * important in @mpx_udiv@, but it is here because of the sign correction.
361 MP_DEST(r, MP_LEN(a) + 2, a->f | b->f);
363 /* --- Fix up the quotient too --- */
366 MP_DEST(q, MP_LEN(r), r->f | MP_UNDEF);
369 /* --- Set up some temporary workspace --- */
372 size_t rq = MP_LEN(b) + 1;
373 sv = mpalloc(r->a, rq);
377 /* --- Perform the calculation --- */
379 mpx_udiv(q->v, q->vl, r->v, r->vl, b->v, b->vl, sv, svl);
381 /* --- Sort out the sign of the results --- *
383 * If the signs of the arguments differ, and the remainder is nonzero, I
384 * must add one to the absolute value of the quotient and subtract the
385 * remainder from @b@.
388 q->f = ((r->f | b->f) & MP_BURN) | ((r->f ^ b->f) & MP_NEG);
391 for (v = r->v; v < r->vl; v++) {
393 MPX_UADDN(q->v, q->vl, 1);
394 mpx_usub(r->v, r->vl, b->v, b->vl, r->v, r->vl);
400 r->f = ((r->f | b->f) & MP_BURN) | (b->f & MP_NEG);
402 /* --- Store the return values --- */
422 /* --- @mp_odd@ --- *
424 * Arguments: @mp *d@ = pointer to destination integer
425 * @mp *m@ = pointer to source integer
426 * @size_t *s@ = where to store the power of 2
428 * Returns: An odd integer integer %$t$% such that %$m = 2^s t$%.
430 * Use: Computes a power of two and an odd integer which, when
431 * multiplied, give a specified result. This sort of thing is
432 * useful in number theory quite often.
435 mp *mp_odd(mp *d, mp *m, size_t *s)
442 for (; !*v && v < vl; v++)
449 unsigned z = MPW_BITS / 2;
462 return (mp_lsr(d, m, ss));
465 /*----- Test rig ----------------------------------------------------------*/
469 static int verify(const char *op, mp *expect, mp *result, mp *a, mp *b)
471 if (!MP_EQ(expect, result)) {
472 fprintf(stderr, "\n*** %s failed", op);
473 fputs("\n*** a = ", stderr); mp_writefile(a, stderr, 10);
474 fputs("\n*** b = ", stderr); mp_writefile(b, stderr, 10);
475 fputs("\n*** result = ", stderr); mp_writefile(result, stderr, 10);
476 fputs("\n*** expect = ", stderr); mp_writefile(expect, stderr, 10);
483 #define RIG(name, op) \
484 static int t##name(dstr *v) \
486 mp *a = *(mp **)v[0].buf; \
487 mpw n = *(int *)v[1].buf; \
489 mp *r = *(mp **)v[2].buf; \
490 mp *c = op(MP_NEW, a, n); \
492 mp_build(&b, &n, &n + 1); \
493 ok = verify(#name, r, c, a, &b); \
494 mp_drop(a); mp_drop(c); mp_drop(r); \
495 assert(mparena_count(MPARENA_GLOBAL) == 0); \
504 #define RIG(name, op) \
505 static int t##name(dstr *v) \
507 mp *a = *(mp **)v[0].buf; \
508 mp *b = *(mp **)v[1].buf; \
509 mp *r = *(mp **)v[2].buf; \
510 mp *c = op(MP_NEW, a, b); \
511 int ok = verify(#name, r, c, a, b); \
512 mp_drop(a); mp_drop(b); mp_drop(c); mp_drop(r); \
513 assert(mparena_count(MPARENA_GLOBAL) == 0); \
523 static int tdiv(dstr *v)
525 mp *a = *(mp **)v[0].buf;
526 mp *b = *(mp **)v[1].buf;
527 mp *q = *(mp **)v[2].buf;
528 mp *r = *(mp **)v[3].buf;
529 mp *c = MP_NEW, *d = MP_NEW;
531 mp_div(&c, &d, a, b);
532 ok &= verify("div(quotient)", q, c, a, b);
533 ok &= verify("div(remainder)", r, d, a, b);
534 mp_drop(a); mp_drop(b); mp_drop(c); mp_drop(d); mp_drop(r); mp_drop(q);
535 assert(mparena_count(MPARENA_GLOBAL) == 0);
539 static int todd(dstr *v)
541 mp *a = *(mp **)v[0].buf;
542 size_t rs = *(uint32 *)v[1].buf;
543 mp *rt = *(mp **)v[2].buf;
547 t = mp_odd(MP_NEW, a, &s);
548 if (s != rs || !MP_EQ(t, rt)) {
550 fprintf(stderr, "\n*** odd failed");
551 fputs("\n*** a = ", stderr); mp_writefile(a, stderr, 10);
552 fprintf(stderr, "\n*** s = %lu", (unsigned long)s);
553 fputs("\n*** t = ", stderr); mp_writefile(t, stderr, 10);
554 fprintf(stderr, "\n*** rs = %lu", (unsigned long)rs);
555 fputs("\n*** rt = ", stderr); mp_writefile(rt, stderr, 10);
564 static test_chunk tests[] = {
565 { "lsl", tlsl, { &type_mp, &type_mp, &type_mp, 0 } },
566 { "lsr", tlsr, { &type_mp, &type_mp, &type_mp, 0 } },
567 { "add", tadd, { &type_mp, &type_mp, &type_mp, 0 } },
568 { "sub", tsub, { &type_mp, &type_mp, &type_mp, 0 } },
569 { "mul", tmul, { &type_mp, &type_mp, &type_mp, 0 } },
570 { "div", tdiv, { &type_mp, &type_mp, &type_mp, &type_mp, 0 } },
571 { "odd", todd, { &type_mp, &type_uint32, &type_mp, 0 } },
575 int main(int argc, char *argv[])
578 test_run(argc, argv, tests, SRCDIR "/tests/mp");
584 /*----- That's all, folks -------------------------------------------------*/