📄 imath.c
字号:
/* Name: imath.c Purpose: Arbitrary precision integer arithmetic routines. Author: M. J. Fromberger <http://www.dartmouth.edu/~sting/> Info: $Id: imath.c 22648 2008-02-25 07:37:57Z lha $ Copyright (C) 2002-2007 Michael J. Fromberger, All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */#include "imath.h"#if DEBUG#include <stdio.h>#endif#include <stdlib.h>#include <string.h>#include <ctype.h>#include <assert.h>#if DEBUG#define static#endif/* {{{ Constants */const mp_result MP_OK = 0; /* no error, all is well */const mp_result MP_FALSE = 0; /* boolean false */const mp_result MP_TRUE = -1; /* boolean true */const mp_result MP_MEMORY = -2; /* out of memory */const mp_result MP_RANGE = -3; /* argument out of range */const mp_result MP_UNDEF = -4; /* result undefined */const mp_result MP_TRUNC = -5; /* output truncated */const mp_result MP_BADARG = -6; /* invalid null argument */const mp_sign MP_NEG = 1; /* value is strictly negative */const mp_sign MP_ZPOS = 0; /* value is non-negative */static const char *s_unknown_err = "unknown result code";static const char *s_error_msg[] = { "error code 0", "boolean true", "out of memory", "argument out of range", "result undefined", "output truncated", "invalid null argument", NULL};/* }}} *//* Argument checking macros Use CHECK() where a return value is required; NRCHECK() elsewhere */#define CHECK(TEST) assert(TEST)#define NRCHECK(TEST) assert(TEST)/* {{{ Logarithm table for computing output sizes *//* The ith entry of this table gives the value of log_i(2). An integer value n requires ceil(log_i(n)) digits to be represented in base i. Since it is easy to compute lg(n), by counting bits, we can compute log_i(n) = lg(n) * log_i(2). The use of this table eliminates a dependency upon linkage against the standard math libraries. */static const double s_log2[] = { 0.000000000, 0.000000000, 1.000000000, 0.630929754, /* 0 1 2 3 */ 0.500000000, 0.430676558, 0.386852807, 0.356207187, /* 4 5 6 7 */ 0.333333333, 0.315464877, 0.301029996, 0.289064826, /* 8 9 10 11 */ 0.278942946, 0.270238154, 0.262649535, 0.255958025, /* 12 13 14 15 */ 0.250000000, 0.244650542, 0.239812467, 0.235408913, /* 16 17 18 19 */ 0.231378213, 0.227670249, 0.224243824, 0.221064729, /* 20 21 22 23 */ 0.218104292, 0.215338279, 0.212746054, 0.210309918, /* 24 25 26 27 */ 0.208014598, 0.205846832, 0.203795047, 0.201849087, /* 28 29 30 31 */ 0.200000000, 0.198239863, 0.196561632, 0.194959022, /* 32 33 34 35 */ 0.193426404, 0.191958720, 0.190551412, 0.189200360, /* 36 37 38 39 */ 0.187901825, 0.186652411, 0.185449023, 0.184288833, /* 40 41 42 43 */ 0.183169251, 0.182087900, 0.181042597, 0.180031327, /* 44 45 46 47 */ 0.179052232, 0.178103594, 0.177183820, 0.176291434, /* 48 49 50 51 */ 0.175425064, 0.174583430, 0.173765343, 0.172969690, /* 52 53 54 55 */ 0.172195434, 0.171441601, 0.170707280, 0.169991616, /* 56 57 58 59 */ 0.169293808, 0.168613099, 0.167948779, 0.167300179, /* 60 61 62 63 */ 0.166666667};/* }}} *//* {{{ Various macros *//* Return the number of digits needed to represent a static value */#define MP_VALUE_DIGITS(V) \((sizeof(V)+(sizeof(mp_digit)-1))/sizeof(mp_digit))/* Round precision P to nearest word boundary */#define ROUND_PREC(P) ((mp_size)(2*(((P)+1)/2)))/* Set array P of S digits to zero */#define ZERO(P, S) \do{mp_size i__=(S)*sizeof(mp_digit);mp_digit *p__=(P);memset(p__,0,i__);}while(0)/* Copy S digits from array P to array Q */#define COPY(P, Q, S) \do{mp_size i__=(S)*sizeof(mp_digit);mp_digit *p__=(P),*q__=(Q);\memcpy(q__,p__,i__);}while(0)/* Reverse N elements of type T in array A */#define REV(T, A, N) \do{T *u_=(A),*v_=u_+(N)-1;while(u_<v_){T xch=*u_;*u_++=*v_;*v_--=xch;}}while(0)#if TRACEABLE_CLAMP#define CLAMP(Z) s_clamp(Z)#else#define CLAMP(Z) \do{mp_int z_=(Z);mp_size uz_=MP_USED(z_);mp_digit *dz_=MP_DIGITS(z_)+uz_-1;\while(uz_ > 1 && (*dz_-- == 0)) --uz_;MP_USED(z_)=uz_;}while(0)#endif#define MIN(A, B) ((B)<(A)?(B):(A))#define MAX(A, B) ((B)>(A)?(B):(A))#define SWAP(T, A, B) do{T t_=(A);A=(B);B=t_;}while(0)#define TEMP(K) (temp + (K))#define SETUP(E, C) \do{if((res = (E)) != MP_OK) goto CLEANUP; ++(C);}while(0)#define CMPZ(Z) \(((Z)->used==1&&(Z)->digits[0]==0)?0:((Z)->sign==MP_NEG)?-1:1)#define UMUL(X, Y, Z) \do{mp_size ua_=MP_USED(X),ub_=MP_USED(Y);mp_size o_=ua_+ub_;\ZERO(MP_DIGITS(Z),o_);\(void) s_kmul(MP_DIGITS(X),MP_DIGITS(Y),MP_DIGITS(Z),ua_,ub_);\MP_USED(Z)=o_;CLAMP(Z);}while(0)#define USQR(X, Z) \do{mp_size ua_=MP_USED(X),o_=ua_+ua_;ZERO(MP_DIGITS(Z),o_);\(void) s_ksqr(MP_DIGITS(X),MP_DIGITS(Z),ua_);MP_USED(Z)=o_;CLAMP(Z);}while(0)#define UPPER_HALF(W) ((mp_word)((W) >> MP_DIGIT_BIT))#define LOWER_HALF(W) ((mp_digit)(W))#define HIGH_BIT_SET(W) ((W) >> (MP_WORD_BIT - 1))#define ADD_WILL_OVERFLOW(W, V) ((MP_WORD_MAX - (V)) < (W))/* }}} *//* {{{ Default configuration settings *//* Default number of digits allocated to a new mp_int */#if IMATH_TESTmp_size default_precision = MP_DEFAULT_PREC;#elsestatic const mp_size default_precision = MP_DEFAULT_PREC;#endif/* Minimum number of digits to invoke recursive multiply */#if IMATH_TESTmp_size multiply_threshold = MP_MULT_THRESH;#elsestatic const mp_size multiply_threshold = MP_MULT_THRESH;#endif/* }}} *//* Allocate a buffer of (at least) num digits, or return NULL if that couldn't be done. */static mp_digit *s_alloc(mp_size num);/* Release a buffer of digits allocated by s_alloc(). */static void s_free(void *ptr);/* Insure that z has at least min digits allocated, resizing if necessary. Returns true if successful, false if out of memory. */static int s_pad(mp_int z, mp_size min);/* Normalize by removing leading zeroes (except when z = 0) */#if TRACEABLE_CLAMPstatic void s_clamp(mp_int z);#endif/* Fill in a "fake" mp_int on the stack with a given value */static void s_fake(mp_int z, int value, mp_digit vbuf[]);/* Compare two runs of digits of given length, returns <0, 0, >0 */static int s_cdig(mp_digit *da, mp_digit *db, mp_size len);/* Pack the unsigned digits of v into array t */static int s_vpack(int v, mp_digit t[]);/* Compare magnitudes of a and b, returns <0, 0, >0 */static int s_ucmp(mp_int a, mp_int b);/* Compare magnitudes of a and v, returns <0, 0, >0 */static int s_vcmp(mp_int a, int v);/* Unsigned magnitude addition; assumes dc is big enough. Carry out is returned (no memory allocated). */static mp_digit s_uadd(mp_digit *da, mp_digit *db, mp_digit *dc, mp_size size_a, mp_size size_b);/* Unsigned magnitude subtraction. Assumes dc is big enough. */static void s_usub(mp_digit *da, mp_digit *db, mp_digit *dc, mp_size size_a, mp_size size_b);/* Unsigned recursive multiplication. Assumes dc is big enough. */static int s_kmul(mp_digit *da, mp_digit *db, mp_digit *dc, mp_size size_a, mp_size size_b);/* Unsigned magnitude multiplication. Assumes dc is big enough. */static void s_umul(mp_digit *da, mp_digit *db, mp_digit *dc, mp_size size_a, mp_size size_b);/* Unsigned recursive squaring. Assumes dc is big enough. */static int s_ksqr(mp_digit *da, mp_digit *dc, mp_size size_a);/* Unsigned magnitude squaring. Assumes dc is big enough. */static void s_usqr(mp_digit *da, mp_digit *dc, mp_size size_a);/* Single digit addition. Assumes a is big enough. */static void s_dadd(mp_int a, mp_digit b);/* Single digit multiplication. Assumes a is big enough. */static void s_dmul(mp_int a, mp_digit b);/* Single digit multiplication on buffers; assumes dc is big enough. */static void s_dbmul(mp_digit *da, mp_digit b, mp_digit *dc, mp_size size_a);/* Single digit division. Replaces a with the quotient, returns the remainder. */static mp_digit s_ddiv(mp_int a, mp_digit b);/* Quick division by a power of 2, replaces z (no allocation) */static void s_qdiv(mp_int z, mp_size p2);/* Quick remainder by a power of 2, replaces z (no allocation) */static void s_qmod(mp_int z, mp_size p2);/* Quick multiplication by a power of 2, replaces z. Allocates if necessary; returns false in case this fails. */static int s_qmul(mp_int z, mp_size p2);/* Quick subtraction from a power of 2, replaces z. Allocates if necessary; returns false in case this fails. */static int s_qsub(mp_int z, mp_size p2);/* Return maximum k such that 2^k divides z. */static int s_dp2k(mp_int z);/* Return k >= 0 such that z = 2^k, or -1 if there is no such k. */static int s_isp2(mp_int z);/* Set z to 2^k. May allocate; returns false in case this fails. */static int s_2expt(mp_int z, int k);/* Normalize a and b for division, returns normalization constant */static int s_norm(mp_int a, mp_int b);/* Compute constant mu for Barrett reduction, given modulus m, result replaces z, m is untouched. */static mp_result s_brmu(mp_int z, mp_int m);/* Reduce a modulo m, using Barrett's algorithm. */static int s_reduce(mp_int x, mp_int m, mp_int mu, mp_int q1, mp_int q2);/* Modular exponentiation, using Barrett reduction */static mp_result s_embar(mp_int a, mp_int b, mp_int m, mp_int mu, mp_int c);/* Unsigned magnitude division. Assumes |a| > |b|. Allocates temporaries; overwrites a with quotient, b with remainder. */static mp_result s_udiv(mp_int a, mp_int b);/* Compute the number of digits in radix r required to represent the given value. Does not account for sign flags, terminators, etc. */static int s_outlen(mp_int z, mp_size r);/* Guess how many digits of precision will be needed to represent a radix r value of the specified number of digits. Returns a value guaranteed to be no smaller than the actual number required. */static mp_size s_inlen(int len, mp_size r);/* Convert a character to a digit value in radix r, or -1 if out of range */static int s_ch2val(char c, int r);/* Convert a digit value to a character */static char s_val2ch(int v, int caps);/* Take 2's complement of a buffer in place */static void s_2comp(unsigned char *buf, int len);/* Convert a value to binary, ignoring sign. On input, *limpos is the bound on how many bytes should be written to buf; on output, *limpos is set to the number of bytes actually written. */static mp_result s_tobin(mp_int z, unsigned char *buf, int *limpos, int pad);#if DEBUG/* Dump a representation of the mp_int to standard output */void s_print(char *tag, mp_int z);void s_print_buf(char *tag, mp_digit *buf, mp_size num);#endif/* {{{ mp_int_init(z) */mp_result mp_int_init(mp_int z){ if(z == NULL) return MP_BADARG; z->single = 0; z->digits = &(z->single); z->alloc = 1; z->used = 1; z->sign = MP_ZPOS; return MP_OK;}/* }}} *//* {{{ mp_int_alloc() */mp_int mp_int_alloc(void){ mp_int out = malloc(sizeof(mpz_t)); if(out != NULL) mp_int_init(out); return out;}/* }}} *//* {{{ mp_int_init_size(z, prec) */mp_result mp_int_init_size(mp_int z, mp_size prec){ CHECK(z != NULL); if(prec == 0) prec = default_precision; else if(prec == 1) return mp_int_init(z); else prec = (mp_size) ROUND_PREC(prec); if((MP_DIGITS(z) = s_alloc(prec)) == NULL) return MP_MEMORY; z->digits[0] = 0; MP_USED(z) = 1; MP_ALLOC(z) = prec; MP_SIGN(z) = MP_ZPOS; return MP_OK;}/* }}} *//* {{{ mp_int_init_copy(z, old) */mp_result mp_int_init_copy(mp_int z, mp_int old){ mp_result res; mp_size uold; CHECK(z != NULL && old != NULL); uold = MP_USED(old); if(uold == 1) { mp_int_init(z); } else { mp_size target = MAX(uold, default_precision); if((res = mp_int_init_size(z, target)) != MP_OK) return res; } MP_USED(z) = uold; MP_SIGN(z) = MP_SIGN(old); COPY(MP_DIGITS(old), MP_DIGITS(z), uold); return MP_OK;}/* }}} *//* {{{ mp_int_init_value(z, value) */mp_result mp_int_init_value(mp_int z, int value){ mpz_t vtmp; mp_digit vbuf[MP_VALUE_DIGITS(value)]; s_fake(&vtmp, value, vbuf); return mp_int_init_copy(z, &vtmp);}/* }}} *//* {{{ mp_int_set_value(z, value) */mp_result mp_int_set_value(mp_int z, int value){ mpz_t vtmp; mp_digit vbuf[MP_VALUE_DIGITS(value)]; s_fake(&vtmp, value, vbuf); return mp_int_copy(&vtmp, z);}/* }}} *//* {{{ mp_int_clear(z) */void mp_int_clear(mp_int z){ if(z == NULL) return; if(MP_DIGITS(z) != NULL) { if((void *) MP_DIGITS(z) != (void *) z) s_free(MP_DIGITS(z)); MP_DIGITS(z) = NULL; }}/* }}} *//* {{{ mp_int_free(z) */void mp_int_free(mp_int z){ NRCHECK(z != NULL); mp_int_clear(z); free(z); /* note: NOT s_free() */}/* }}} *//* {{{ mp_int_copy(a, c) */mp_result mp_int_copy(mp_int a, mp_int c){ CHECK(a != NULL && c != NULL); if(a != c) { mp_size ua = MP_USED(a); mp_digit *da, *dc; if(!s_pad(c, ua)) return MP_MEMORY; da = MP_DIGITS(a); dc = MP_DIGITS(c); COPY(da, dc, ua); MP_USED(c) = ua; MP_SIGN(c) = MP_SIGN(a); } return MP_OK;}/* }}} *//* {{{ mp_int_swap(a, c) */void mp_int_swap(mp_int a, mp_int c){ if(a != c) { mpz_t tmp = *a; *a = *c; *c = tmp; }}/* }}} *//* {{{ mp_int_zero(z) */void mp_int_zero(mp_int z){ NRCHECK(z != NULL); z->digits[0] = 0; MP_USED(z) = 1; MP_SIGN(z) = MP_ZPOS;}/* }}} *//* {{{ mp_int_abs(a, c) */mp_result mp_int_abs(mp_int a, mp_int c){ mp_result res; CHECK(a != NULL && c != NULL); if((res = mp_int_copy(a, c)) != MP_OK) return res; MP_SIGN(c) = MP_ZPOS; return MP_OK;}/* }}} *//* {{{ mp_int_neg(a, c) */mp_result mp_int_neg(mp_int a, mp_int c){ mp_result res; CHECK(a != NULL && c != NULL); if((res = mp_int_copy(a, c)) != MP_OK) return res; if(CMPZ(c) != 0) MP_SIGN(c) = 1 - MP_SIGN(a); return MP_OK;}/* }}} *//* {{{ mp_int_add(a, b, c) */mp_result mp_int_add(mp_int a, mp_int b, mp_int c){ mp_size ua, ub, uc, max; CHECK(a != NULL && b != NULL && c != NULL); ua = MP_USED(a); ub = MP_USED(b); uc = MP_USED(c); max = MAX(ua, ub); if(MP_SIGN(a) == MP_SIGN(b)) { /* Same sign -- add magnitudes, preserve sign of addends */ mp_digit carry; if(!s_pad(c, max)) return MP_MEMORY; carry = s_uadd(MP_DIGITS(a), MP_DIGITS(b), MP_DIGITS(c), ua, ub); uc = max; if(carry) { if(!s_pad(c, max + 1)) return MP_MEMORY; c->digits[max] = carry; ++uc; } MP_USED(c) = uc; MP_SIGN(c) = MP_SIGN(a); } else { /* Different signs -- subtract magnitudes, preserve sign of greater */ mp_int x, y; int cmp = s_ucmp(a, b); /* magnitude comparision, sign ignored */ /* Set x to max(a, b), y to min(a, b) to simplify later code */ if(cmp >= 0) { x = a; y = b; } else { x = b; y = a; } if(!s_pad(c, MP_USED(x))) return MP_MEMORY; /* Subtract smaller from larger */ s_usub(MP_DIGITS(x), MP_DIGITS(y), MP_DIGITS(c), MP_USED(x), MP_USED(y)); MP_USED(c) = MP_USED(x); CLAMP(c); /* Give result the sign of the larger */ MP_SIGN(c) = MP_SIGN(x); } return MP_OK;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -