3 * $Id: mp-arith.c,v 1.11 2002/10/06 22:52:50 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.11 2002/10/06 22:52:50 mdw
34 * Pile of changes for supporting two's complement properly.
36 * Revision 1.10 2001/04/03 19:36:05 mdw
37 * Add some simple bitwise operations so that Perl can use them.
39 * Revision 1.9 2000/10/08 15:48:35 mdw
40 * Rename Karatsuba constants now that we have @gfx_kmul@ too.
42 * Revision 1.8 2000/10/08 12:02:21 mdw
43 * Use @MP_EQ@ instead of @MP_CMP@.
45 * Revision 1.7 2000/06/22 19:02:53 mdw
46 * New function @mp_odd@ to extract powers of two from an integer. This is
47 * common code from the Rabin-Miller test, RSA key recovery and modular
48 * square-root extraction.
50 * Revision 1.6 2000/06/17 11:45:09 mdw
51 * Major memory management overhaul. Added arena support. Use the secure
52 * arena for secret integers. Replace and improve the MP management macros
53 * (e.g., replace MP_MODIFY by MP_DEST).
55 * Revision 1.5 1999/12/22 15:54:41 mdw
56 * Adjust Karatsuba parameters. Calculate destination size better.
58 * Revision 1.4 1999/12/13 15:35:16 mdw
59 * Slightly different rules on memory allocation.
61 * Revision 1.3 1999/12/11 10:57:43 mdw
62 * Karatsuba squaring algorithm.
64 * Revision 1.2 1999/12/10 23:18:39 mdw
65 * Change interface for suggested destinations.
67 * Revision 1.1 1999/11/17 18:02:16 mdw
68 * New multiprecision integer arithmetic suite.
72 /*----- Header files ------------------------------------------------------*/
76 /*----- Macros ------------------------------------------------------------*/
78 #define MAX(x, y) ((x) >= (y) ? (x) : (y))
80 /*----- Main code ---------------------------------------------------------*/
82 /* --- @mp_lsl@, @mp_lsr@ --- *
84 * Arguments: @mp *d@ = destination
86 * @size_t n@ = number of bits to move
88 * Returns: Result, @a@ shifted left or right by @n@.
91 mp
*mp_lsl(mp
*d
, mp
*a
, size_t n
)
93 MP_DEST(d
, MP_LEN(a
) + (n
+ MPW_BITS
- 1) / MPW_BITS
, a
->f
);
94 mpx_lsl(d
->v
, d
->vl
, a
->v
, a
->vl
, n
);
95 d
->f
= a
->f
& (MP_NEG
| MP_BURN
);
100 mp
*mp_lsr(mp
*d
, mp
*a
, size_t n
)
102 MP_DEST(d
, MP_LEN(a
), a
->f
);
103 mpx_lsr(d
->v
, d
->vl
, a
->v
, a
->vl
, n
);
104 d
->f
= a
->f
& (MP_NEG
| MP_BURN
);
109 /* --- @mp_lsl2c@, @mp_lsr2c@ --- *
111 * Arguments: @mp *d@ = destination
113 * @size_t n@ = number of bits to move
115 * Returns: Result, @a@ shifted left or right by @n@. Handles the
116 * pretence of sign-extension for negative numbers.
119 mp
*mp_lsl2c(mp
*d
, mp
*a
, size_t n
)
121 if (!(a
->f
& MP_NEG
))
122 return (mp_lsl(d
, a
, n
));
129 mp
*mp_lsr2c(mp
*d
, mp
*a
, size_t n
)
131 if (!(a
->f
& MP_NEG
))
132 return (mp_lsr(d
, a
, n
));
139 /* --- @mp_testbit@ --- *
141 * Arguments: @mp *x@ = a large integer
142 * @size_t n@ = which bit to test
144 * Returns: Nonzero if the bit is set, zero if not.
147 int mp_testbit(mp
*x
, size_t n
)
150 if (n
> MPW_BITS
* MP_LEN(x
))
154 return ((x
->v
[o
] >> n
) & 1);
157 /* --- @mp_testbit2c@ --- *
159 * Arguments: @mp *x@ = a large integer
160 * @size_t n@ = which bit to test
162 * Returns: Nonzero if the bit is set, zero if not. Fakes up two's
163 * complement representation.
166 int mp_testbit2c(mp
*x
, size_t n
)
170 return (mp_testbit(x
, n
));
171 x
= mp_not2c(MP_NEW
, x
);
172 r
= !mp_testbit(x
, n
);
179 * Arguments: @const mp *a, *b@ = two numbers
181 * Returns: Nonzero if the numbers are equal.
184 int mp_eq(const mp
*a
, const mp
*b
) { return (MP_EQ(a
, b
)); }
186 /* --- @mp_cmp@ --- *
188 * Arguments: @const mp *a, *b@ = two numbers
190 * Returns: Less than, equal to or greater than zero, according to
191 * whether @a@ is less than, equal to or greater than @b@.
194 int mp_cmp(const mp
*a
, const mp
*b
)
196 if (!((a
->f
^ b
->f
) & MP_NEG
))
197 return (mpx_ucmp(a
->v
, a
->vl
, b
->v
, b
->vl
));
198 else if (a
->f
& MP_NEG
)
204 /* --- @mp_bitop@ --- *
206 * Arguments: @mp *d@ = destination
207 * @mp *a, *b@ = sources
209 * Returns: The result of the given bitwise operation. These functions
210 * don't handle negative numbers at all sensibly. For that, use
211 * the @...2c@ variants. The functions are named after the
212 * truth tables they generate:
219 #define MP_BITBINOP(string) \
221 mp *mp_bit##string(mp *d, mp *a, mp *b) \
223 MP_DEST(d, MAX(MP_LEN(a), MP_LEN(b)), a->f | b->f); \
224 mpx_bit##string(d->v, d->vl, a->v, a->vl, b->v, b->vl); \
225 d->f = (a->f | b->f) & MP_BURN; \
230 MPX_DOBIN(MP_BITBINOP
)
232 /* --- @mp_not@ --- *
234 * Arguments: @mp *d@ = destination
237 * Returns: The bitwise complement of the source.
240 mp
*mp_not(mp
*d
, mp
*a
)
242 MP_DEST(d
, MP_LEN(a
), a
->f
);
243 mpx_not(d
->v
, d
->vl
, a
->v
, a
->vl
);
244 d
->f
= a
->f
& MP_BURN
;
249 /* --- @mp_bitop2c@ --- *
251 * Arguments: @mp *d@ = destination
252 * @mp *a, *b@ = sources
254 * Returns: The result of the given bitwise operation. Negative numbers
255 * are treated as two's complement, sign-extended infinitely to
256 * the left. The functions are named after the truth tables
264 /* --- How this actually works --- *
266 * The two arguments are inverted (with a sign-swap) if they're currently
267 * negative. This means that we end up using a different function (one which
268 * reinverts as we go) for the main operation. Also, if the sign would be
269 * negative at the end, we preinvert the output and then invert again with a
272 * Start with: wxyz WXYZ
273 * If @a@ negative: yzwx or YZWX
274 * If @b@ negative: xwzy XWZY
275 * If both negative: zyxw ZYXW
278 #define MP_BIT2CBINOP(n, base, an, bn, abn, p_base, p_an, p_bn, p_abn) \
280 mp *mp_bit##n##2c(mp *d, mp *a, mp *b) \
282 if (!((a->f | b->f) & MP_NEG)) { /* Both positive */ \
283 d = mp_bit##base(d, a, b); \
285 } else if (!(b->f & MP_NEG)) { /* Only @b@ positive */ \
287 d = mp_not2c(d, a); \
288 d = mp_bit##an(d, d, b); \
291 } else if (!(a->f & MP_NEG)) { /* Only @a@ positive */ \
293 d = mp_not2c(d, b); \
294 d = mp_bit##bn(d, a, d); \
297 } else { /* Both negative */ \
298 mp *t = mp_not2c(MP_NEW, a); \
299 mp *d = mp_not2c(d, b); \
300 d = mp_bit##abn(d, t, d); \
307 #define NEG d = mp_not2c(d, d);
309 MP_BIT2CBINOP(0000, 0000, 0000, 0000, 0000, POS
, POS
, POS
, POS
)
310 MP_BIT2CBINOP(0001, 0001, 0100, 0010, 0111, POS
, POS
, POS
, NEG
)
311 MP_BIT2CBINOP(0010, 0010, 0111, 0001, 0100, POS
, NEG
, POS
, POS
)
312 MP_BIT2CBINOP(0011, 0011, 0011, 0011, 0011, POS
, NEG
, POS
, NEG
)
313 MP_BIT2CBINOP(0100, 0100, 0001, 0111, 0010, POS
, POS
, NEG
, POS
)
314 MP_BIT2CBINOP(0101, 0101, 0101, 0101, 0101, POS
, POS
, NEG
, NEG
)
315 MP_BIT2CBINOP(0110, 0110, 0110, 0110, 0110, POS
, NEG
, NEG
, POS
)
316 MP_BIT2CBINOP(0111, 0111, 0010, 0100, 0001, POS
, NEG
, NEG
, NEG
)
317 MP_BIT2CBINOP(1000, 0111, 0010, 0100, 0001, NEG
, POS
, POS
, POS
)
318 MP_BIT2CBINOP(1001, 0110, 0110, 0110, 0110, NEG
, POS
, POS
, NEG
)
319 MP_BIT2CBINOP(1010, 0101, 0101, 0101, 0101, NEG
, NEG
, POS
, POS
)
320 MP_BIT2CBINOP(1011, 0100, 0001, 0111, 0010, NEG
, NEG
, POS
, NEG
)
321 MP_BIT2CBINOP(1100, 0011, 0011, 0011, 0011, NEG
, POS
, NEG
, POS
)
322 MP_BIT2CBINOP(1101, 0010, 0111, 0001, 0100, NEG
, POS
, NEG
, NEG
)
323 MP_BIT2CBINOP(1110, 0001, 0100, 0010, 0111, NEG
, NEG
, NEG
, POS
)
324 MP_BIT2CBINOP(1111, 0000, 0000, 0000, 0000, NEG
, NEG
, NEG
, NEG
)
328 /* --- @mp_not2c@ --- *
330 * Arguments: @mp *d@ = destination
333 * Returns: The sign-extended complement of the argument.
336 mp
*mp_not2c(mp
*d
, mp
*a
)
340 MP_DEST(d
, MP_LEN(a
) + 1, a
->f
);
343 MPX_USUBN(d
->v
, d
->vl
, 1);
345 MPX_UADDN(d
->v
, d
->vl
, 1);
348 mpx_usub(d
->v
, d
->vl
, a
->v
, a
->vl
, &one
, &one
+ 1);
350 mpx_uadd(d
->v
, d
->vl
, a
->v
, a
->vl
, &one
, &one
+ 1);
352 d
->f
= (a
->f
& (MP_NEG
| MP_BURN
)) ^ MP_NEG
;
357 /* --- @mp_add@ --- *
359 * Arguments: @mp *d@ = destination
360 * @mp *a, *b@ = sources
362 * Returns: Result, @a@ added to @b@.
365 mp
*mp_add(mp
*d
, mp
*a
, mp
*b
)
367 MP_DEST(d
, MAX(MP_LEN(a
), MP_LEN(b
)) + 1, a
->f
| b
->f
);
368 if (!((a
->f
^ b
->f
) & MP_NEG
))
369 mpx_uadd(d
->v
, d
->vl
, a
->v
, a
->vl
, b
->v
, b
->vl
);
371 if (MPX_UCMP(a
->v
, a
->vl
, <, b
->v
, b
->vl
)) {
372 mp
*t
= a
; a
= b
; b
= t
;
374 mpx_usub(d
->v
, d
->vl
, a
->v
, a
->vl
, b
->v
, b
->vl
);
376 d
->f
= ((a
->f
| b
->f
) & MP_BURN
) | (a
->f
& MP_NEG
);
381 /* --- @mp_sub@ --- *
383 * Arguments: @mp *d@ = destination
384 * @mp *a, *b@ = sources
386 * Returns: Result, @b@ subtracted from @a@.
389 mp
*mp_sub(mp
*d
, mp
*a
, mp
*b
)
392 MP_DEST(d
, MAX(MP_LEN(a
), MP_LEN(b
)) + 1, a
->f
| b
->f
);
393 if ((a
->f
^ b
->f
) & MP_NEG
)
394 mpx_uadd(d
->v
, d
->vl
, a
->v
, a
->vl
, b
->v
, b
->vl
);
396 if (MPX_UCMP(a
->v
, a
->vl
, <, b
->v
, b
->vl
)) {
397 mp
*t
= a
; a
= b
; b
= t
;
400 mpx_usub(d
->v
, d
->vl
, a
->v
, a
->vl
, b
->v
, b
->vl
);
402 d
->f
= ((a
->f
| b
->f
) & MP_BURN
) | ((a
->f
^ sgn
) & MP_NEG
);
407 /* --- @mp_mul@ --- *
409 * Arguments: @mp *d@ = destination
410 * @mp *a, *b@ = sources
412 * Returns: Result, @a@ multiplied by @b@.
415 mp
*mp_mul(mp
*d
, mp
*a
, mp
*b
)
420 if (MP_LEN(a
) <= MPK_THRESH
|| MP_LEN(b
) <= MPK_THRESH
) {
421 MP_DEST(d
, MP_LEN(a
) + MP_LEN(b
), a
->f
| b
->f
| MP_UNDEF
);
422 mpx_umul(d
->v
, d
->vl
, a
->v
, a
->vl
, b
->v
, b
->vl
);
424 size_t m
= 2 * MAX(MP_LEN(a
), MP_LEN(b
)) + 2;
426 MP_DEST(d
, m
, a
->f
| b
->f
| MP_UNDEF
);
428 s
= mpalloc(d
->a
, m
);
429 mpx_kmul(d
->v
, d
->vl
, a
->v
, a
->vl
, b
->v
, b
->vl
, s
, s
+ m
);
433 d
->f
= ((a
->f
| b
->f
) & MP_BURN
) | ((a
->f
^ b
->f
) & MP_NEG
);
440 /* --- @mp_sqr@ --- *
442 * Arguments: @mp *d@ = destination
445 * Returns: Result, @a@ squared.
448 mp
*mp_sqr(mp
*d
, mp
*a
)
450 size_t m
= MP_LEN(a
);
453 MP_DEST(d
, 2 * m
+ 2, a
->f
| MP_UNDEF
);
454 if (m
> MPK_THRESH
) {
456 m
= 2 * (m
+ 1) + MPK_SLOP
;
457 s
= mpalloc(d
->a
, m
);
458 mpx_ksqr(d
->v
, d
->vl
, a
->v
, a
->vl
, s
, s
+ m
);
461 mpx_usqr(d
->v
, d
->vl
, a
->v
, a
->vl
);
462 d
->f
= a
->f
& MP_BURN
;
468 /* --- @mp_div@ --- *
470 * Arguments: @mp **qq, **rr@ = destination, quotient and remainder
471 * @mp *a, *b@ = sources
473 * Use: Calculates the quotient and remainder when @a@ is divided by
474 * @b@. The destinations @*qq@ and @*rr@ must be distinct.
475 * Either of @qq@ or @rr@ may be null to indicate that the
476 * result is irrelevant. (Discarding both results is silly.)
477 * There is a performance advantage if @a == *rr@.
479 * The behaviour when @a@ and @b@ have the same sign is
480 * straightforward. When the signs differ, this implementation
481 * chooses @r@ to have the same sign as @b@, rather than the
482 * more normal choice that the remainder has the same sign as
483 * the dividend. This makes modular arithmetic a little more
487 void mp_div(mp
**qq
, mp
**rr
, mp
*a
, mp
*b
)
489 mp
*r
= rr ?
*rr
: MP_NEW
;
490 mp
*q
= qq ?
*qq
: MP_NEW
;
493 /* --- Set the remainder up right --- *
495 * Just in case the divisor is larger, be able to cope with this. It's not
496 * important in @mpx_udiv@, but it is here because of the sign correction.
504 MP_DEST(r
, MP_LEN(a
) + 2, a
->f
| b
->f
);
506 /* --- Fix up the quotient too --- */
509 MP_DEST(q
, MP_LEN(r
), r
->f
| MP_UNDEF
);
512 /* --- Set up some temporary workspace --- */
515 size_t rq
= MP_LEN(b
) + 1;
516 sv
= mpalloc(r
->a
, rq
);
520 /* --- Perform the calculation --- */
522 mpx_udiv(q
->v
, q
->vl
, r
->v
, r
->vl
, b
->v
, b
->vl
, sv
, svl
);
524 /* --- Sort out the sign of the results --- *
526 * If the signs of the arguments differ, and the remainder is nonzero, I
527 * must add one to the absolute value of the quotient and subtract the
528 * remainder from @b@.
531 q
->f
= ((r
->f
| b
->f
) & MP_BURN
) | ((r
->f
^ b
->f
) & MP_NEG
);
534 for (v
= r
->v
; v
< r
->vl
; v
++) {
536 MPX_UADDN(q
->v
, q
->vl
, 1);
537 mpx_usub(r
->v
, r
->vl
, b
->v
, b
->vl
, r
->v
, r
->vl
);
543 r
->f
= ((r
->f
| b
->f
) & MP_BURN
) | (b
->f
& MP_NEG
);
545 /* --- Store the return values --- */
565 /* --- @mp_odd@ --- *
567 * Arguments: @mp *d@ = pointer to destination integer
568 * @mp *m@ = pointer to source integer
569 * @size_t *s@ = where to store the power of 2
571 * Returns: An odd integer integer %$t$% such that %$m = 2^s t$%.
573 * Use: Computes a power of two and an odd integer which, when
574 * multiplied, give a specified result. This sort of thing is
575 * useful in number theory quite often.
578 mp
*mp_odd(mp
*d
, mp
*m
, size_t *s
)
585 for (; !*v
&& v
< vl
; v
++)
592 unsigned z
= MPW_BITS
/ 2;
605 return (mp_lsr(d
, m
, ss
));
608 /*----- Test rig ----------------------------------------------------------*/
612 static int verify(const char *op
, mp
*expect
, mp
*result
, mp
*a
, mp
*b
)
614 if (!MP_EQ(expect
, result
)) {
615 fprintf(stderr
, "\n*** %s failed", op
);
616 fputs("\n*** a = ", stderr
); mp_writefile(a
, stderr
, 10);
617 fputs("\n*** b = ", stderr
); mp_writefile(b
, stderr
, 10);
618 fputs("\n*** result = ", stderr
); mp_writefile(result
, stderr
, 10);
619 fputs("\n*** expect = ", stderr
); mp_writefile(expect
, stderr
, 10);
626 #define RIG(name, op) \
627 static int t##name(dstr *v) \
629 mp *a = *(mp **)v[0].buf; \
630 mpw n = *(int *)v[1].buf; \
632 mp *r = *(mp **)v[2].buf; \
633 mp *c = op(MP_NEW, a, n); \
635 mp_build(&b, &n, &n + 1); \
636 ok = verify(#name, r, c, a, &b); \
637 mp_drop(a); mp_drop(c); mp_drop(r); \
638 assert(mparena_count(MPARENA_GLOBAL) == 0); \
649 #define RIG(name, op) \
650 static int t##name(dstr *v) \
652 mp *a = *(mp **)v[0].buf; \
653 mp *b = *(mp **)v[1].buf; \
654 mp *r = *(mp **)v[2].buf; \
655 mp *c = op(MP_NEW, a, b); \
656 int ok = verify(#name, r, c, a, b); \
657 mp_drop(a); mp_drop(b); mp_drop(c); mp_drop(r); \
658 assert(mparena_count(MPARENA_GLOBAL) == 0); \
668 static int tdiv(dstr
*v
)
670 mp
*a
= *(mp
**)v
[0].buf
;
671 mp
*b
= *(mp
**)v
[1].buf
;
672 mp
*q
= *(mp
**)v
[2].buf
;
673 mp
*r
= *(mp
**)v
[3].buf
;
674 mp
*c
= MP_NEW
, *d
= MP_NEW
;
676 mp_div(&c
, &d
, a
, b
);
677 ok
&= verify("div(quotient)", q
, c
, a
, b
);
678 ok
&= verify("div(remainder)", r
, d
, a
, b
);
679 mp_drop(a
); mp_drop(b
); mp_drop(c
); mp_drop(d
); mp_drop(r
); mp_drop(q
);
680 assert(mparena_count(MPARENA_GLOBAL
) == 0);
684 static int tbin(dstr
*v
)
686 static mp
*(*fn
[])(mp
*, mp
*, mp
*) = {
687 #define DO(string) mp_bit##string##2c,
693 mp
*a
= *(mp
**)v
[1].buf
;
694 mp
*b
= *(mp
**)v
[2].buf
;
695 mp
*r
= *(mp
**)v
[3].buf
;
698 if (strcmp(v
[0].buf
, "and") == 0) op
= 1;
699 else if (strcmp(v
[0].buf
, "or") == 0) op
= 7;
700 else if (strcmp(v
[0].buf
, "nand") == 0) op
= 14;
701 else if (strcmp(v
[0].buf
, "nor") == 0) op
= 8;
702 else if (strcmp(v
[0].buf
, "xor") == 0) op
= 6;
712 c
= fn
[op
](MP_NEW
, a
, b
);
713 ok
= verify(v
[0].buf
, r
, c
, a
, b
);
714 mp_drop(a
); mp_drop(b
); mp_drop(r
); mp_drop(c
);
715 assert(mparena_count(MPARENA_GLOBAL
) == 0);
719 static int todd(dstr
*v
)
721 mp
*a
= *(mp
**)v
[0].buf
;
722 size_t rs
= *(uint32
*)v
[1].buf
;
723 mp
*rt
= *(mp
**)v
[2].buf
;
727 t
= mp_odd(MP_NEW
, a
, &s
);
728 if (s
!= rs
|| !MP_EQ(t
, rt
)) {
730 fprintf(stderr
, "\n*** odd failed");
731 fputs("\n*** a = ", stderr
); mp_writefile(a
, stderr
, 10);
732 fprintf(stderr
, "\n*** s = %lu", (unsigned long)s
);
733 fputs("\n*** t = ", stderr
); mp_writefile(t
, stderr
, 10);
734 fprintf(stderr
, "\n*** rs = %lu", (unsigned long)rs
);
735 fputs("\n*** rt = ", stderr
); mp_writefile(rt
, stderr
, 10);
744 static test_chunk tests
[] = {
745 { "lsl", tlsl
, { &type_mp
, &type_int
, &type_mp
, 0 } },
746 { "lsr", tlsr
, { &type_mp
, &type_int
, &type_mp
, 0 } },
747 { "lsl2c", tlsl2c
, { &type_mp
, &type_int
, &type_mp
, 0 } },
748 { "lsr2c", tlsr2c
, { &type_mp
, &type_int
, &type_mp
, 0 } },
749 { "add", tadd
, { &type_mp
, &type_mp
, &type_mp
, 0 } },
750 { "sub", tsub
, { &type_mp
, &type_mp
, &type_mp
, 0 } },
751 { "mul", tmul
, { &type_mp
, &type_mp
, &type_mp
, 0 } },
752 { "div", tdiv
, { &type_mp
, &type_mp
, &type_mp
, &type_mp
, 0 } },
753 { "bin2c", tbin
, { &type_string
, &type_mp
, &type_mp
, &type_mp
, 0 } },
754 { "odd", todd
, { &type_mp
, &type_uint32
, &type_mp
, 0 } },
758 int main(int argc
, char *argv
[])
761 test_run(argc
, argv
, tests
, SRCDIR
"/tests/mp");
767 /*----- That's all, folks -------------------------------------------------*/