LIBTOMMATH(3)

NAME
libtommath - a big integer library

SYNOPSIS

#include <tommath.h>

DESCRIPTION
LibTomMath provides a series of efficient and carefully written functions for manipulating large integer numbers.
Functions are in alphabetical order.

NOTE: The errors listed are not the only ones possible, just the interesting ones.

mp_err mp_2expt(mp_int * a, int b)
Computes 2^b with b >= 0 and puts the result in a. This functions uses a faster method than mp_mul_2.
Returns MP_OVF if the result would be larger than a mp_int can hold. The macro MP_MAX_DIGIT_COUNT holds the maximal number of limbs: ((INT_MAX - 2) / MP_DIGIT_BIT).
Returns MP_VAL if b < 0

mp_err mp_abs (const mp_int *a, mp_int *b)
Computes the absolute value of a and puts the result in b.

mp_err mp_add (const mp_int *a, const mp_int *b, mp_int *c)
Computes a + b = c.

mp_err mp_add_d(const mp_int *a, mp_digit b, mp_int *c)
Computes a + b = c where b is of type mp_digit.

mp_err mp_addmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d)
Computes (a + b) % c = d. No optimizations.

mp_err mp_and (const mp_int *a, mp_int *b, mp_int *c)
Computes bitwise or a & b = c. Negative numbers are treated as if they are in two-complement representation.

void mp_clamp(mp_int *a);
This is used to ensure that leading zero digits are trimmed and the leading used digit will be non-zero. It also fixes the sign if there are no more leading digits.

void mp_clear (mp_int *a)
Frees the heap memory of a.

int mp_cnt_lsb(const mp_int *a)
Returns the position of the lowest bit set.

mp_ord mp_cmp(const mp_int *a, const mp_int *b)
Compare a to b.

mp_ord mp_cmp_d(const mp_int *a, mp_digit b)
Compare a to a single digit b.

mp_ord mp_cmp_mag(const mp_int *a, const mp_int *b)
Compares the absolute values of a and b.

mp_err mp_complement(const mp_int *a, mp_int *b)
Computes the 2-complement b = ~a.

mp_err mp_copy (const mp_int *a, mp_int *b)
Makes a deep copy of a into b.

int mp_count_bits(const mp_int *a)
Returns the position of the highest bit set.

mp_err mp_decr(mp_int *a)
Computes a--.

mp_err mp_div_2(const mp_int *a, mp_int *b);
Computes a >> 1 = b.

mp_err mp_div_2d (const mp_int *a, int b, mp_int *c, mp_int *d);
Computes a >> b = c + d with c the optional quotient and d the optional remainder.
Set the argument for quotient and/or remainder to NULL to ignore the respective output.
Returns MP_VAL if b < 0

mp_err mp_div (const mp_int *a, const mp_int *b, mp_int *c, mp_int *d)
Computes a / b = c + d with c the optional quotient and d the optional remainder.
Set the argument for quotient and/or remainder to NULL to ignore the respective output.
This function calls one of either: s_mp_div_recursive, s_mp_div_school, or s_mp_div_small.
Returns MP_VAL if b = 0

mp_err mp_div_d(const mp_int *a, mp_digit b, mp_int *c, mp_digit *d)
Computes a / b = c + d with c the optional quotient and d the optional remainder.
Set the argument for quotient and/or remainder to NULL to ignore the respective output. Returns MP_VAL if b = 0.

bool mp_dr_is_modulus(const mp_int *a)
Returns true if the modulus a is of the form below that allows for a diminished radix reduction, false otherwise.
β^k - p for some k >= 0 and 0 < p < β where β is the radix.

mp_err mp_dr_reduce(mp_int *a, const mp_int *b, mp_digit mp)
This reduces a in place modulo b with the pre-computed value mp. b must be of a restricted diminished radix form and a must be in the range 0 <= a < b^2

void mp_dr_setup(const mp_int *a, mp_digit *d)
This computes the value required for the modulus a and stores it in d.

void mp_exch (mp_int *a, mp_int *b)
Swaps, but just the pointers.

const char *mp_error_to_string(mp_err code)
Returns a short ASCII message describing the error code given in code.

mp_err mp_exptmod (const mp_int *G, const mp_int *X, const mp_int *P, mp_int *Y)
This computes Y ≡ G^X (mod P) using a variable width sliding window algorithm. This function will automatically detect the fastest modular reduction technique to use during the operation. For negative values of X the operation is performed as Y ≡ (G^-1 mod P)^(|X| (mod P)) provided that gcd(G, P) = 1.
This function is actually a shell around the two internal exponentiation functions. This routine will automatically detect when Barrett, Montgomery, Restricted and Unrestricted Diminished Radix based exponentiation can be used. Generally moduli of the a "restricted diminished radix" form lead to the fastest modular exponentiations. Followed by Montgomery and the other two algorithms.
Returns MP_VAL if P < 0.
Returns MP_VAL if none of the underlying internal functions have been compiled in.

mp_err mp_expt_n(const mp_int *a, int b, int *c)
Computes a^b = c. Simple binary exponentiation, no further optimizations.
b must be positive.

mp_err mp_exteuclid(const mp_int *a, const mp_int *b, mp_int *U1, mp_int *U2, mp_int *U3)
Computes the extended Euclidean algorithm: a * U1 + b * U2 = U3
Set the argument for U1, U2, U3 to NULL to ignore the respective output.

mp_err mp_fread(mp_int *a, int radix, FILE *stream)
Reads a number in radix radix from file stream and converts it into the big integer a.
Returns MP_VAL if radix is not in the range 2 <= radix <= 64.
Returns MP_ERR if no digits were found in stream.

mp_err mp_from_sbin(mp_int *a, const uint8_t *b, size_t size)
This will read in an big-endian array of octets from b of length size into a.
If the first octet of the data is zero, the sign of the big-integer will be MP_NEG and MP_ZPOS otherwise.

mp_err mp_from_ubin(mp_int *a, uint8_t *b, size_t size)
This will read in an big-endian array of octets from b of length size into a. The resulting big-integer a will always be positive.

mp_err mp_fwrite(const mp_int *a, int radix, FILE *stream)
Writes a as a string representing the big integer in radix radix to file stream.
Returns MP_MEM if the functions fails to allocate memory for the buffer.
Returns MP_ERR if there was a problem writing to the file.
Returns MP_VAL if radix is not in the range 2 <= radix <= 64.

mp_err mp_gcd (const mp_int *a, const mp_int *b, mp_int *c)
Compute the greatest common divisor of a and b and store it in c.

double mp_get_double(const mp_int *a)
Returns a float of type double (binary64).
Will overflow if the big integer is too big.
NOTE: rounding mode is not set just taken. Use e.g.: fesetround(3) in fenv.h to change the rounding mode.

int32_t mp_get_i32 (const mp_int *a)
Returns a signed 32-bit integer from big-integer a.
NOTE: This group of functions is truncating. Example:
Input | 123456789101112131415161718192021222324252627282930
mp_get_i32 | -1073632270
mp_get_i64 | 5543444065158278130
mp_get_mag_u32 | 3221335026
mp_get_mag_u64 | 5543444065158278130
mp_get_l | 5543444065158278130
mp_get_ul | 5543444065158278130
mp_get_mag_ul | 5543444065158278130

int64_t mp_get_i64 (const mp_int *a)
Returns a signed 64-bit integer from big-integer a.
NOTE: This function is truncating. See mp_get_i32 for details.

long mp_get_l (const mp_int *a)
Returns a signed long from big-integer a.
NOTE: This function is truncating. See mp_get_i32 for details.

uint32_t mp_get_mag_u32 (const mp_int *a)
Returns an unsigned 32 bit integer from big-integer a.
NOTE: This function is truncating. See mp_get_i32 for details.

uint64_t mp_get_mag_u64 (const mp_int *a)
Returns an unsigned 64 bit integer from big-integer a.
NOTE: This function is truncating. See mp_get_i32 for details.

unsigned long mp_get_mag_ul (const mp_int *a)
Returns an unsigned long from big-integer a.
NOTE: This function is truncating. See mp_get_i32 for details.

uint32_t mp_get_u32 (const mp_int *a)
Convenience macro for mp_get_mag_u32().

uint64_t mp_get_u64 (const mp_int *a)
Convenience macro for mp_get_mag_u64().

unsigned long mp_get_ul (const mp_int *a)
Convenience macro for mp_get_mag_ul().

mp_err mp_grow (mp_int *a, int size)
This will grow the array of digits of a to size.
Returns MP_MEM if the functions fails to allocate enough memory.

mp_err mp_hash (const mp_int *a, mp_hval *hash)
This will create the hash of a following the FNV-1a algorithm as described on http://www.isthe.com/chongo/tech/comp/fnv/index.html#FNV-1a. With the help of this function one can use an mp_int as a key in a hash table.
NOTE: The hashing is not stable over different widths of a mp_digit.

mp_err mp_incr(mp_int *a)
Computes a++.
Returns MP_MEM if the reallocation of memory in mp_grow failed.

mp_err mp_init_copy (mp_int *a, mp_int *b)
Initializes a and copies b into a.

mp_err mp_init_i32 (mp_int *a, int32_t b);
Initializes a and copies the signed 32 bit integer b into a.

mp_err mp_init_i64 (mp_int *a, int64_t b)
Initializes a and copies the signed 64 bit integer b into a.

mp_err mp_init_l (mp_int *a, long b)
Initializes a and copies the signed integer b of type long into a.

mp_err mp_init (mp_int *a)
Initializes a.
It allocates a certain amount of memory such that the mp_set_u64 setter can store an uint64_t in the mp_int. To be able to take advantage of the algorithm used for mp_school_div the mp_int must have at least three limbs.
It actively sets all limbs to zero, overwriting what was there before, sets the a.sign to MP_ZPOS, and a.used to zero.

mp_err mp_init_multi(mp_int *mp, ...)
Initialize a NULL terminated series of mp_ints.

mp_err mp_init_set (mp_int *a, mp_digit b)
Initializes a and sets it to the mp_digit b

mp_err mp_init_size (mp_int *a, int size)
Initializes a with pre-grown to a size number of limbs.
If size is smaller than the minimum (see mp_init for details) size will be increased to that minimum.
Returns MP_OVF if size is larger than an mp_int is able to hold.

mp_err mp_init_u32 (mp_int *a, uint32_t b)
Initializes a and copies the unsigned 32 bit integer b into a.

mp_err mp_init_u64 (mp_int *a, uint64_t b)
Initializes a and copies the unsigned 64 bit integer b into a.

mp_err mp_init_ul (mp_int *a, unsigned long b)
Initializes a and copies the unsigned integer b of type unsigned long into a.

mp_err mp_invmod (const mp_int *a, const mp_int *b, mp_int *c)
Computes the multiplicative inverse of a modulo b and stores the result in v such that ac ≡ 1 (mod b).
Does use a faster algorithm if the modulus b is odd.
Returns MP_VAL if b <= 1

bool mp_iseven(const mp_int *a)
Returns true if a is even, false otherwise.

bool mp_isneg(mp_int *a)
Returns true if a < 0, false otherwise.

bool mp_isodd(const mp_int *a)
Returns true if a is odd, false otherwise.

mp_err mp_is_square(const mp_int *arg, bool *ret)
Sets ret to true if arg is a square, false otherwise.

bool mp_iszero(mp_int *a)
Returns true if a = 0, false otherwise.

bool mp_isone(mp_int *a)
Returns true if a = 1, false otherwise.

mp_err mp_kronecker (const mp_int *a, const mp_int *p, int *c)
Computes the Kronecker symbol (an extension of the Jacobi symbol) for a with respect to p with (a, p) in Z. If p is prime this essentially computes the Legendre symbol. The result is stored in c and can take on one of three values {-1, 0, 1}.
-1 | if a is not a quadratic residue modulo p and p is prime.
0 | if a divides p
1 | if a is a quadratic residue modulo p.

mp_err mp_lcm (const mp_int *a, const mp_int *b, mp_int *c)
Computes the least common multiple as |a * b|/gcd(a, b).

mp_err mp_log(const mp_int *a, const mp_int *base, int *c)
Computes log_b(a) such that (log_b a)^b <= a.
Returns MP_VAL if a <= 0 or b < 2.

mp_err mp_log_n(const mp_int *a, int base, int *c)
Computes log_b(a) such that (log_b a)^b <= a.
Convenience function that is a wrapper for mp_log doing the conversion of b to a big integer.

mp_err mp_lshd (mp_int *a, int b)
Shift a left by b limbs: a * 2^(b*MP_DIGIT_BIT).

mp_err mp_mod_2d(const mp_int *a, int b, mp_int *c)
Compute a % 2^b.

mp_err mp_mod(const mp_int *a,const mp_int *b, mp_int *c)
Compute a ≡ c mod b.
0 <= c < b if b > 0 and b < c <= 0 if b < 0.

mp_err mp_mod_d(const mp_int *a, mp_digit b, mp_digit *c)
Computes the remainder of a / b.

mp_err mp_montgomery_calc_normalization(mp_int *a, mp_int *b)
Computes R = r^n for Montgomery reduction where n is size of a in bits and r is the radix (MP_DIGIT_MAX + 1).
See mp_montgomery_reduce for some example code.

mp_err mp_montgomery_reduce(mp_int *a, mp_int *m, mp_digit mp)
Reduces a in place modulo m with the pre-computed value mp (a*mp^(-1) ≡ x (mod m) ). Pre-computation of mp can be done with mp_montgomery_setup. Example:
int main(void)
{
   mp_int   a, b, c, R;
   mp_digit mp;
   mp_err      result;
   /* initialize a,b to desired values,
    * mp_init R, c and set c to 1....
    */
   /* get normalization */
   if ((result = mp_montgomery_calc_normalization(&R, b)) != MP_OKAY) {
      printf("Error getting norm.  %s",
             mp_error_to_string(result));
      return EXIT_FAILURE;
   }
   /* get mp value */
   if ((result = mp_montgomery_setup(&c, &mp)) != MP_OKAY) {
      printf("Error setting up montgomery.  %s",
             mp_error_to_string(result));
      return EXIT_FAILURE;
   }
   /* normalize `a' so now a is equal to aR */
   if ((result = mp_mulmod(&a, &R, &b, &a)) != MP_OKAY) {
      printf("Error computing aR.  %s",
             mp_error_to_string(result));
      return EXIT_FAILURE;
   }
   /* square a to get c = a^2R^2 */
   if ((result = mp_sqr(&a, &c)) != MP_OKAY) {
      printf("Error squaring.  %s",
             mp_error_to_string(result));
      return EXIT_FAILURE;
   }
   /* now reduce `c' back down to c = a^2R^2 * R^-1 == a^2R */
   if ((result = mp_montgomery_reduce(&c, &b, mp)) != MP_OKAY) {
      printf("Error reducing.  %s",
             mp_error_to_string(result));
      return EXIT_FAILURE;
   }
   /* multiply a to get c = a^3R^2 */
   if ((result = mp_mul(&a, &c, &c)) != MP_OKAY) {
      printf("Error reducing.  %s",
             mp_error_to_string(result));
      return EXIT_FAILURE;
   }
   /* now reduce `c' back down to c = a^3R^2 * R^-1 == a^3R */
   if ((result = mp_montgomery_reduce(&c, &b, mp)) != MP_OKAY) {
      printf("Error reducing.  %s",
             mp_error_to_string(result));
      return EXIT_FAILURE;
   }
   /* now reduce (again) `c' back down to c = a^3R * R^-1 == a^3 */
   if ((result = mp_montgomery_reduce(&c, &b, mp)) != MP_OKAY) {
      printf("Error reducing.  %s",
             mp_error_to_string(result));
      return EXIT_FAILURE;
   }
   /* c now equals a^3 mod b */
   return EXIT_SUCCESS;

mp_err mp_montgomery_setup(const mp_int *a, mp_digit *mp)
For the given odd modulus a the pre-computation value is placed in mp.
mp = 1/a mod 2^k with k the number of bits in the underlying native type used for mp_digit.
See mp_montgomery_reduce for some example code.

mp_err mp_mul_2(const mp_int *a, mp_int *b)
Computes b = 2 * a.

mp_err mp_mul_2d(const mp_int *a, int b, mp_int *c)
Shifts a left by b bits b = a * 2^b.
Condition: b >= 0

mp_err mp_mul (const mp_int *a, const mp_int *b, mp_int *c)
Computes c = a * b.

mp_err mp_mul_d(const mp_int *a, mp_digit b, mp_int *c)
Computes c = a * b with b and mp_digit.

mp_err mp_mulmod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d)
Computes d = a * b (mod c). No optimizations.
For special forms of the input libtommath offers other, optimized algorithms. See for example
mp_montgomery_reduce for some example code with Montgomery reduction. There is also Barret
reduction, which is more generic (mp_reduce), diminished radix reduction (mp_dr_reduce) and
unrestricted diminished radix reduction (mp_reduce_2k)

mp_err mp_neg (const mp_int *a, mp_int *b)
Computes b = -a.

mp_err mp_or  (const mp_int *a, mp_int *b, mp_int *c)
Computes bit-wise or a | b = c. Negative numbers
are treated as if they are in two-complement representation.

size_t mp_pack_count(const mp_int *a, size_t nails, size_t size)
Returns the size in bytes necessary to be put in mp_pack's maxsize. See mp_pack for details.

mp_err mp_pack(void *rop, size_t *countp, mp_order order, size_t size, mp_endian endian, size_t nails, const mp_int *op)
Export binary data.
Implements the similarly working GMP functions as described at http://gmplib.org/manual/Integer-Import-and-Export.html with
the exception that mp_pack will not allocate memory if rop is NULL.
To make things a bit more comfortable libtommath offers two enums:
typedef enum {
   MP_LSB_FIRST = -1,
   MP_MSB_FIRST =  1
} mp_order;
typedef enum {
   MP_LITTLE_ENDIAN  = -1,
   MP_NATIVE_ENDIAN  =  0,
   MP_BIG_ENDIAN     =  1
} mp_ndian;

mp_err mp_prime_fermat(const mp_int *a, const mp_int *b, bool *result)
Performs one Fermat test of a using base b.
Sets result to true if a is probably prime, false if composite.

mp_err mp_prime_strong_lucas_selfridge(const mp_int *a, bool *result)
Sets result to true if a is a strong Lucas-Selfridge pseudoprime, false otherwise.
It has been verified that this function together with one round of Miller-Rabin to the base 2 (two) is
deterministic up to 2^64.

mp_err mp_prime_frobenius_underwood(const mp_int *N, bool *result)
Sets result to true if a is a Frobenius-Underwood pseudoprime, false otherwise.
It has been verified that this function (as a stand-alone) is deterministic up to at least 2^50.

mp_err mp_prime_is_prime(const mp_int *a, int t, bool *result)
Sets result to true if a is a pseudoprime, false otherwise.
The argument t holds the number of random Miller-Rabin tests to be executed.
Uses a stack of different tests to detect composites:

        Direct test: checks if input is one of the values 0, 1, 2.

        The only even prime has been handled, reject even input from now on

        Check if input is a square. (some of the algorithms used later do not like square input)

        Check if input is equal to one of the primes in the table s_mp_prime_tab

        Check if input is divisible by one of the primes in the table s_mp_prime_tab

        Run a Miller-Rabin test with base 2

        Run a Miller-Rabin test with base 3

        If t <= 0 and the macro LTM_USE_ONLY_MR is not defined we run either a Frobenius-Underwood
        test if the macro LTM_USE_FROBENIUS_TEST is defined or a Lucas-Selfridge test.
        The Lucas-Selfridge test together with the two Miller-Rabin tests earlier is deterministic up to at least 2^64.
        The Frobenius-Underwood test as a stand-alone is deterministic up to at least 2^50. But it is different from
        the Lucas-Selfridge test so the additional cost (about two times the time a Lucas-Selfridge test would need) might be worthwhile.

        Even if t = 0 we run at least one Miler-Rabin test with a random base.

        If t < 0 and input smaller than 3,317,044,064,679,887,385,961,981 (< 82 bits) several Miller-Rabin tests
        are run with bases according to Sorenson, Jonathan; Webster, Jonathan (2015) "Strong Pseudoprimes to Twelve Prime Bases".
        Here ends the deterministic part of this function.

        If t > 0: run the given number of Miller-Rabin tests with random bases.

mp_err mp_prime_miller_rabin (const mp_int *a, const mp_int *b, int *result)
Run the Miller-Rabin pseudoprime test of a with base b and set result to true
if a is a strong pseudprime for base b and false otherwise.

mp_err mp_prime_next_prime(mp_int *a, int t, bool bbs_style)
Sets a to the next prime, even if a is prime itself.
Argument t holds the number of Miller-Rabin tests to random bases and can also be used to steer
mp_prime_is_prime as described there.
Argument bbs_style returns only primes a ≡ 3 (mod 4) if set to true.

mp_err mp_prime_rabin_miller_trials(int size)
Returns the number of Miller-Rabin tests to random bases necessary for RSA according to
FIPS 186-4.
size is the size of the prime in bits.
The entries are pre-computed:
<=size | #tests | Error
80 | -1 | Use deterministic algorithm for size <= 80 bits
81 | 37 | 2^(-96)
96 | 32 | 2^(-96)
128 | 40 | 2^(-112)
160 | 35 | 2^(-112)
256 | 27 | 2^(-128)
384 | 16 | 2^(-128)
512 | 18 | 2^(-160)
768 | 11 | 2^(-160)
896 | 10 | 2^(-160)
1024 | 12 | 2^(-192)
1536 | 8 | 2^(-192)
2048 | 6 | 2^(-192)
3072 | 4 | 2^(-192)
4096 | 5 | 2^(-256)
5120 | 4 | 2^(-256)
6144 | 4 | 2^(-256)
8192 | 3 | 2^(-256)
9216 | 3 | 2^(-256)
10240 | 2 | For bigger keysizes use always at least 2 Rounds

mp_err mp_prime_rand(mp_int *a, int t, int size, int flags)
Generates a random big prime a with size bits.
Argument t holds the number of Miller-Rabin tests to random bases and can also be used to steer
mp_prime_is_prime as described there.
Argument flags determines the kind of prime:
Flag | Condition
MP_PRIME_BBS | make prime congruent to 3 mod 4
MP_PRIME_SAFE | make sure (p-1)/2 is prime as well (implies MP_PRIME_BBS)
MP_PRIME_2MSB_ON | make the 2nd highest bit one

mp_err mp_radix_size (const mp_int *a, int radix, int *size)
Sets size to the length of the ASCII string of the representation of big integer a in radix radix.
This includes the sign and the terminatong NUL.
Returns MP_VAL if radix is not in the range 2 <= radix <= 64

mp_err mp_radix_size_overestimate (const mp_int *a, int radix, int *size)
Same as mp_radix_size but uses a rough, table based approximation instead of calling mp_log_n.
Overestimates the result by some units: relative error is about 10^(-8). Experiments showed that
the absolute error should not go pass 5.

mp_err mp_rand(mp_int *a, int digits)
Generates a random big integer a with a digits number of limbs.
NOTE: This function uses the same (P)RNG as the prime generating/testing functions. If that entropy
is precious see mp_rand_source to set another (P)RNG.

void mp_rand_source(mp_err(*source)(void *out, size_t size));
Sets the (P)RNG used for all functions in Libtommath, that need some random bytes.
Set source to NULL to get the original (Libtommath) source back.
Example:
uint32_t prng_state = 0xdeadbeef;
uint32_t bad_prng(void) {
   prng_state = (1103515245ul * prng_state  + 12345ul) % 2147483648ul;
   return prng_state;
}
mp_err myprng(void *p, size_t n)
{
   char *q = (char *)p;
   while (n > 0u) {
      int i;
      uint32_t x = bad_prng();
      for (i = 0; (i < 4) && (n > 0u); ++i, --n) {
         *q++ = (char)(x & 0xFFu);
         x >>= 8;
      }
   }
   return MP_OKAY;
}
mp_err some_monte_carlo_function(...)
{
   /* Use the the bad but fast P(R)NG */
   mp_rand_source(myprng);
   ...
   while(big_number--) {
      mp_rand(a_bigint, n_bits);
      ...
   }
   /* Reset and use (P)RNG provided by the platform */
   mp_rand_source(NULL);
   ...
}

mp_err mp_read_radix (mp_int *a, const char *str, int radix)
This will read a NUL terminated string in base radix from str into a.
Returns MP_VAL if radix is not in the range 2 <= radix <= 64.

mp_err mp_reduce_2k_l(mp_int *a, const mp_int *n, const mp_int *d)
Reduces a modulo n where n is of the form 2^p - d where d
is a big integer.
Belongs to the "unrestricted diminished radix reduction" method.

mp_err mp_reduce_2k(mp_int *a, const mp_int *n, mp_digit d)
Reduces a modulo n where n is of the form 2^p - d where d
is a mp_digit.
Belongs to the "unrestricted diminished radix reduction" method.

mp_err mp_reduce_2k_setup(const mp_int *a, mp_digit *d)
This will compute the required d value in 2^p - d for the given moduli a where d
is a mp_digit.
Belongs to the "unrestricted diminished radix reduction" method.

mp_err mp_reduce_2k_setup_l(const mp_int *a, mp_int *d)
This will compute the required d value in 2^p - d for the given moduli a where d
is a big integer.
Belongs to the "unrestricted diminished radix reduction" method.

mp_err mp_reduce(const mp_int *a, const mp_int *b, mp_int *c)
This will reduce a in place modulo b with the precomputed mu value in c.  amust be in
the range 0 <= a < b^2.
Belongs to the "Barrett reduction" method.

bool mp_reduce_is_2k(const mp_int *a)
Determines if mp_reduce_2k can be used with a mp_digit.
Belongs to the "unrestricted diminished radix reduction" method.

bool mp_reduce_is_2k_l(const mp_int *a)
Determines if mp_reduce_2k can be used with a big integer.
Belongs to the "unrestricted diminished radix reduction" method.

mp_err mp_reduce_setup(const mp_int *a, mp_int *b)
Compute mu for Barrett reduction.

mp_err mp_root_n(const mp_int *a, int b, mp_int *c)
This computes c = a^(1/b) such that c^b <= a and (c+1)^b > a. Will return a positive root
only for even roots and return a root with the sign of the input for odd roots.  For example,
performing 4^(1/2) will return 2 whereas (-8)^(1/3) will return -2.
Returns MP_VAL if b < 0 or b > MP_DIGIT_MAX or when b is even and a < 0.

void mp_rshd (mp_int *a, int b)
Shift a right by b limbs: a / 2^(b*MP_DIGIT_BIT).

size_t mp_sbin_size(const mp_int *a)
Returns the number of bytes (octets) required to store the signed copy of the integer a.

mp_err mp_set_double(mp_int *a, double b)
If the platform supports the floating point data type double (binary64) this function will
assign the integer part of b to the big integer a.
Returns MP_VAL if b is +/-infinity or NaN

void mp_set_i32 (mp_int *a, int32_t b)
Sets big integer a to the value of the signed 32 bit integer b.

void mp_set_i64 (mp_int *a, int64_t b)
Sets big integer a to the value of the signed 64 bit integer b.

void mp_set_l (mp_int *a, long b)
Sets big integer a to the value of the integer b of type signed long.

void mp_set (mp_int *a, mp_digit b)
Sets big integer a to the value of the integer b of type mp_digit.

void mp_set_u32 (mp_int *a, uint32_t b)
Sets big integer a to the value of the unsigned 32 bit integer b.

void mp_set_u64 (mp_int *a, uint64_t b)
Sets big integer a to the value of the unsigned 64 bit integer b.

void mp_set_ul (mp_int *a, unsigned long b)
Sets big integer a to the value of the integer b of type unsigned long.

mp_err mp_shrink (mp_int *a)
This will remove excess digits of the mp_int a.
This method uses realloc with all its problems, use with caution.

mp_err mp_signed_rsh(const mp_int *a, int b, mp_int *c)
Shifts right a by b bits with sign extension.

mp_err mp_sqr (const mp_int *a, mp_int *b)
Computes a^2 = b

mp_err mp_sqrmod(const mp_int *a, const mp_int *b, const mp_int *c)
Computes a^2 % b = c. No optimization.

mp_err mp_sqrt(const mp_int *arg, mp_int *ret)
Computes a^(1/2) = b such that b^2 <= a.

mp_err mp_sqrtmod_prime(const mp_int *n, const mp_int *p, mp_int *r)
Computesa^(1/2) % p = r with p prime. Uses the Tonelli-Shanks algorithm.
Does do some checks for p but no actual primality test.
The prime p must be odd.

mp_err mp_sub (const mp_int *a, const mp_int *b, mp_int *c)
Computes a - b = c with b a big integer.

mp_err mp_sub_d(const mp_int *a, mp_digit b, mp_int *c)
Computes a - b = c with b of type mp_digit.

mp_err mp_submod(const mp_int *a, const mp_int *b, const mp_int *c, mp_int *d)
Computes (a - b) % c = d. No optimization.

mp_to_binary(M, S, N)
Macro that calls mp_to_radix with fixed radix = 2.

mp_to_decimal(M, S, N)
Macro that calls mp_to_radix with fixed radix = 10.

mp_to_hex(M, S, N)
Macro that calls mp_to_radix with fixed radix = 16.

mp_to_octal(M, S, N)
Macro that calls mp_to_radix with fixed radix = 8.

mp_err mp_to_radix (const mp_int *a, char *str, size_t maxlen, size_t *written, int radix)
Stores upto size - 1 chars and always a NULL byte in str and puts the number of characters written,
including NUL, in written.
The caller is responsible to allocate a sufficient amount of memory for the buffer str. Use mp_radix_size or
mp_radix_size_overestimate to have that number computed.
Returns MP_BUF if maxlen < 2
Return MP_VAL if radix is not in the range 2 <= radix <= 64.

mp_err mp_to_sbin(const mp_int *a, uint8_t *b, size_t maxsize, size_t *len)
Store a maxlen amount of the big integer in buffer b and puts the number of bytes written in len.
If a is negative b0] = 1 and b[0] = 0 otherwise.
Returns MP_BUF if maxlen is too small. Use mp_sbin_size to have that number computed.

mp_err mp_to_ubin(const mp_int *a, uint8_t *buf, size_t maxlen, size_t *written)
Store a maxlen amount of the big integer in buffer b and puts the number of bytes written in len.
Returns MP_BUF if maxlen is too small. Use mp_sbin_size to have that number computed.

size_t mp_ubin_size(const mp_int *a)
Returns the number of bytes (octets) required to store the unsigned copy of the big integer a.

mp_err mp_unpack(mp_int *rop, size_t count, mp_order order, size_t size, mp_endian endian, size_t nails, const void *op)
Implements the similarly working GMP functions as described at http://gmplib.org/manual/Integer-Import-and-Export.html.
See also: mp_pack for more details.

mp_err mp_xor (const mp_int *a, mp_int *b, mp_int *c)
Computes bit-wise xor a ^ b = c. Negative numbers are treated as if they are in two-complement representation.
Returns MP_MEM if the reallocation of memory in mp_grow failed.

void mp_zero(mp_int *a)
Sets a to zero.

  TYPES
mp_digit
An unsigned machine integer able to hold MP_DIGIT_BIT + 1 bits.
This type is defined in tommath.h

mp_word
An unsigned integer able to hold a value of size 2 * MP_DIGIT_MAX + 1. This type is defined in tommath_private.h

mp_int
The internal structure of Libtommath's big integer type mp_int.
typedef struct  {
   int used, alloc;
   mp_sign sign;
   mp_digit *dp;
} mp_int;

mp_sign
The sign of Libtommath's big integer type mp_int
typedef enum {
   MP_ZPOS = 0,   /* positive */
   MP_NEG = 1     /* negative */
} mp_sign;

mp_ord
Results of comparing with the functions mp_cmp() and  mp_cmp_d().
typedef enum {
   MP_LT = -1,    /* less than */
   MP_EQ = 0,     /* equal */
   MP_GT = 1      /* greater than */
} mp_ord;

mp_err
The handful of different errors Libtommath can throw.
typedef enum {
   MP_OKAY  = 0,   /* no error */
   MP_ERR   = -1,  /* unknown error */
   MP_MEM   = -2,  /* out of mem */
   MP_VAL   = -3,  /* invalid input */
   MP_ITER  = -4,  /* maximum iterations reached */
   MP_BUF   = -5,  /* buffer overflow, supplied buffer too small */
   MP_OVF   = -6   /* mp_int overflow, too many digits */
} mp_err;

mp_order
Bit order. If the most signifcant bit comes first or the least significant one.
Not to be mistaken for mp_ord.
typedef enum {
   MP_LSB_FIRST = -1,
   MP_MSB_FIRST =  1
} mp_order;

mp_endian
Byte order. Only big and little endian are supported. MP_NATIVE_ENDIAN refers to the local (detected)
endianess.
typedef enum {
   MP_LITTLE_ENDIAN  = -1,
   MP_NATIVE_ENDIAN  =  0,
   MP_BIG_ENDIAN     =  1
} mp_endian;

hval
Type holding the hash produced by mp_hash. Either a 32 bit or a 64 bit unsigned type.

  MACROS

MP_DIGIT_BIT
The size in bits of a limb.
The value depends on the size of the biggest available native integer type.
arch bits | MP_DIGIT_BIT | MACRO
16 | 15 | MP_16BIT
32 | 28, (31) | MP_32BIT, (MP_31BIT) (1)
64 | 60, (28) | MP_64BIT, (MP_64BIT) (2)
32/64 | 28 | MP_28BIT (3)
(1) The size 31 bit reduces some of the optimizations, especially COMBA.
(2) Some C-compilers do not offer 16 byte integers. One of them is very famous.
(3) Default when all tests to search for something better fail.
NOTE: ISO C 23 introduced _BitInt(n) which would allow 16 byte integers even on non 64 bit architectures. Not much support as of the time of this writing (LLVM does, for example).

MP_PRIME_BBS
Generate a BBS style prime. (See: mp_prime_rand)

MP_PRIME_SAFE
Generate a safe prime such that (p-1)/2 == prime. (See: mp_prime_rand)

MP_PRIME_2MSB_ON
Force 2nd most siginficant bit to be 1 (one). when generating primes. (See: mp_prime_rand)

MP_DIGIT_MAX
Largest value a mp_digit can hold: -1 + 2^MP_DIGIT_BIT.

MP_MASK
Holds the same value as MP_DIGIT_MAX.
NOTE: this macro computes the value, MP_DIGIT_MAX is a copy.

  GLOBAL VARIABLES
Libtommath uses no global variables, it is threadsafe.
But some global variables are there to allow for e.g.: tuning and can hence be abused. But shouldn't.

extern int MP_MUL_KARATSUBA_CUTOFF
Sets the cutoff value when Karatsuba multiplication comes in if the macro MP_FIXED_CUTOFFS is not defined.

extern int MP_SQR_KARATSUBA_CUTOFF
Sets the cutoff value when Karatsuba squaring comes in if the macro MP_FIXED_CUTOFFS is not defined.

extern int MP_MUL_TOOM_CUTOFF
Sets the cutoff value when Toom-Cook 3-way multiplication comes in if the macro MP_FIXED_CUTOFFS is not defined.

extern int MP_SQR_TOOM_CUTOFF
Sets the cutoff value when Toom-Cook 3-way squaring comes in if the macro MP_FIXED_CUTOFFS is not defined.

EXAMPLES

  Is n a Perfect Power
A function that uses a mix of libtommath's functions.
static mp_err mp_is_perfect_power(const mp_int *n, bool *result,
                                    mp_int *rootout, mp_int *exponent)
{
   mp_int root, power, prime, max;
   int highbit, lowbit, p;
   mp_err err = MP_OKAY;
   *result = false;
   /* No negative numbers. For now. */
   if (mp_cmp_d(n, 4) == MP_LT) {
      err = MP_VAL;
      goto LTM_OUT;
   }
   /* Compute floor(log_2(n)) */
   highbit = mp_count_bits(n) - 1;
   /* MP_IS_POWER_OF_TWO(n) is a macro in tommath_private.h */
   if (MP_IS_POWER_OF_TWO(n)) {
      *result = true;
      if (exponent != NULL) {
         if ((err = mp_set_l(exponent, (long)highbit)) != MP_OKAY) {
            return err;
         }
      }
      if (rootout != NULL) {
         if ((err = mp_set_l(rootout, 2l)) != MP_OKAY) {
            return err;
         }
      }
      return err;
   }
   /* Initialize the needed variables all at once */
   if ((err = mp_init_multi(&root, &power, &prime, &max, NULL)) != MP_OKAY) {
      return err;
   }
   /* a long is at least as big as an int */
   if( (err = mp_set_l(&max, (long)highbit) ) != MP_OKAY)                goto LTM_ERR;
   /* mp_prime_next_prime() returns the next prime, so start with a preceding value */
   mp_set(&prime, 2u);
   while (mp_cmp(&prime, &max) != MP_GT) {
      /* Deterministic up to 2^82 but the largest value possible is < INT_MAX       */
      if ((err = mp_prime_next_prime(&prime, -1, false)) != MP_OKAY)     goto LTM_ERR;
      p = (int)mp_get_l(&prime);
      if ((err = mp_root_n(n, p, &root)) != MP_OKAY)                     goto LTM_ERR;
      if ((err = mp_expt_n(&root, p, &power)) != MP_OKAY)                goto LTM_ERR;
      if (mp_cmp(n, &power) == MP_EQ) {
         *result = true;
         if (rootout != NULL) {
            mp_exch(&root, rootout);
         }
         if (exponent != NULL) {
            if ((e = mp_set_l(exponent, (long)p)) != MP_OKAY)            goto LTM_ERR;
         }
      }
   }
LTM_OUT:
   if (rootout != NULL) {
      if ((err = mp_set(rootout, 0u)) != MP_OKAY)                        goto LTM_ERR;
   }
   if (exponent != NULL) {
      if ((err = mp_set(exponent, 0u)) != MP_OKAY)                       goto LTM_ERR;
   }
LTM_ERR:
   mp_clear_multi(&root, &power,&prime,  NULL);
   return err;
}

  Pi by Binary Splitting
Compute digits of pi using Manchin's formula from 1706. A classic.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <limits.h>
#include <tommath.h>
static int mp_acot_binary_splitting(
             mp_int * q, mp_int * a, mp_int * b, mp_int * P,
             mp_int * Q, mp_int * R, int * idx)
{
    mp_err err;
    mp_int p1, q1, r1, p2, q2, r2, t1, t2, one;
    if ((err = mp_init_multi(
                  &p1, &q1, &r1, &p2, &q2,
                  &r2, &t1, &t2, &one, NULL)) != MP_OKAY) {
        return err;
    }
    err = MP_OKAY;
    mp_set(&one, 1);
    if ((err = mp_sub(b, a, &t1)) != MP_OKAY)                 goto LTM_ERR;
    if (mp_cmp(&t1, &one) == MP_EQ) {
        if ((err = mp_mul_2d(a, 1, &t1)) != MP_OKAY)          goto LTM_ERR;
        if ((err = mp_add_d(&t1, 3, &t1)) != MP_OKAY)         goto LTM_ERR;
        mp_set(P, 1);
        if ( ((*idx) & 1) == 0 ) {
            P->sign = MP_NEG;
        }
        (*idx)++;
        if ((err = mp_mul(&t1, q, Q)) != MP_OKAY)             goto LTM_ERR;
        if ((err = mp_copy(&t1, R)) != MP_OKAY)               goto LTM_ERR;
        /* Done */
        goto LTM_ERR;
    }
    if ((err = mp_add(a, b, &t1)) != MP_OKAY)                 goto LTM_ERR;
    if ((err = mp_div_2d(&t1, 1, &t1, NULL)) != MP_OKAY)      goto LTM_ERR;
    if ((err = mp_acot_binary_splitting(
                  q, a, &t1, &p1, &q1, &r1, idx)) != MP_OKAY) goto LTM_ERR;
    if ((err = mp_acot_binary_splitting(
                  q, &t1, b, &p2, &q2, &r2, idx)) != MP_OKAY) goto LTM_ERR;
    /* P = q2*p1 + r1*p2 */
    if ((err = mp_mul(&q2, &p1, &t1)) != MP_OKAY)             goto LTM_ERR;
    if ((err = mp_mul(&r1, &p2, &t2)) != MP_OKAY)             goto LTM_ERR;
    if ((err = mp_add(&t1, &t2, P)) != MP_OKAY)               goto LTM_ERR;
    /* Q =  q1*q2 */
    if ((err = mp_mul(&q1, &q2, Q)) != MP_OKAY)               goto LTM_ERR;
    /* R = r1*r2 */
    if ((err = mp_mul(&r1, &r2, R)) != MP_OKAY)               goto LTM_ERR;
  LTM_ERR:
    mp_clear_multi(&p1, &q1, &r1, &p2, &q2, &r2, &t1, &t2, &one, NULL);
    return err;
}
int main(int argc, char **argv)
{
   mp_int N, P, Q, R, zero, EPS, t1, t2, t5, t239;
   mp_err err = MP_OKAY;
   int idx = 0;
   long eps, dec;
   if(argc != 2) {
     fprintf(stderr, "Usage %s bits of precision", argv[0]);
     exit(EXIT_FAILURE);
   }
   errno = 0;
   eps = strtol(argv[1],NULL,10);
   if ((errno == ERANGE && (eps == LONG_MAX || eps == LONG_MIN))
       || (errno != 0 && eps == 0)) {
      fprintf(stderr,"Error reading precision. Reason: %s,
                     strerror(errno));
      exit(EXIT_FAILURE);
   }
   if( (err = mp_init_multi(
       &N, &P, &Q, &R, &zero, &EPS, &t1, &t2, &t5, &t239, NULL) ) != MP_OKAY) {
      fprintf(stderr,"Error initializing mp_ints. Reason: %s,
                     mp_error_to_string(err));
      exit(EXIT_FAILURE);
   }
   /* Machin's 1706 */
   mp_set(&t5, 5u);
   mp_set(&t239, 239u);
   mp_set_l(&EPS, eps);
   if( (err = mp_sqr(&t5, &t1) ) != MP_OKAY)                      goto LTM_ERR;
   if( (err = mp_acot_binary_splitting(
             &t1, &zero, &EPS, &P, &Q, &R, &idx) ) != MP_OKAY)    goto LTM_ERR;
   if( (err = mp_add(&P, &Q, &t1) ) != MP_OKAY)                   goto LTM_ERR;
   if( (err = mp_mul_2d(&t1, (int)eps, &t1) ) != MP_OKAY)         goto LTM_ERR;
   if( (err = mp_mul(&Q, &t5, &t2) ) != MP_OKAY)                  goto LTM_ERR;
   if( (err = mp_div(&t1, &t2, &t5, NULL) ) != MP_OKAY)           goto LTM_ERR;
   if( (err = mp_sqr(&t239, &t1) ) != MP_OKAY)                    goto LTM_ERR;
   if( (err = mp_acot_binary_splitting(
             &t1, &zero, &EPS, &P, &Q, &R, &idx) ) != MP_OKAY)    goto LTM_ERR;
   if( (err = mp_add(&P, &Q, &t1) ) != MP_OKAY)                   goto LTM_ERR;
   if( (err = mp_mul_2d(&t1, (int)eps, &t1) ) != MP_OKAY)         goto LTM_ERR;
   if( (err = mp_mul(&Q, &t239, &t2) ) != MP_OKAY)                goto LTM_ERR;
   if( (err = mp_div(&t1, &t2, &t239, NULL) ) != MP_OKAY)         goto LTM_ERR;
   if( (err = mp_mul_2d(&t5, 2, &t5) ) != MP_OKAY)                goto LTM_ERR;
   if( (err = mp_sub(&t5, &t239, &t1) ) != MP_OKAY)               goto LTM_ERR;
   if( (err = mp_mul_2d(&t1, 2, &t1) ) != MP_OKAY)                goto LTM_ERR;
   /* 146/485 ~ 1/log_2(10) for about 7 decimal digits */
   dec = (eps * 146) / 485;
   mp_set(&t2, 10);
   if( (err = mp_expt_n(&t2, (int)dec, &t2) ) != MP_OKAY)         goto LTM_ERR;
   if( (err = mp_mul(&t1,&t2,&t1) ) != MP_OKAY)                   goto LTM_ERR;
   if( (err = mp_div_2d(&t1, (int)eps, &t1, NULL) ) != MP_OKAY)   goto LTM_ERR;
   if( (err = mp_fwrite(&t1,10,stdout) ) != MP_OKAY)              goto LTM_ERR;
   mp_clear_multi(&N, &P, &Q, &R, &zero, &EPS, &t1, &t2, &t5, &t239, NULL);
   exit(EXIT_SUCCESS);
LTM_ERR:
   mp_clear_multi(&N, &P, &Q, &R, &zero, &EPS, &t1, &t2, &t5, &t239, NULL);
   exit(EXIT_FAILURE);
}

SEE ALSO
https://github.com/libtom/libtommath

BUGS
Please report all bugs and other incommodities at https://github.com/libtom/libtommath/issues

AUTHORS AND LICENSE
Version 1.2.0

Copyright (C) 2002 Tom St Denis The LibTom license

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.

In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law.

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 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.

For more information, please refer to <http://unlicense.org/>