Module Z
Integers.
This modules provides arbitrary-precision integers. Small integers internally use a regular OCaml int
. When numbers grow too large, we switch transparently to GMP numbers (mpn
numbers fully allocated on the OCaml heap).
This interface is rather similar to that of Int32
and Int64
, with some additional functions provided natively by GMP (GCD, square root, pop-count, etc.).
This file is part of the Zarith library http://forge.ocamlcore.org/projects/zarith . It is distributed under LGPL 2 licensing, with static linking exception. See the LICENSE file included in the distribution.
Copyright (c) 2010-2011 Antoine Miné, Abstraction project. Abstraction is part of the LIENS (Laboratoire d'Informatique de l'ENS), a joint laboratory by: CNRS (Centre national de la recherche scientifique, France), ENS (École normale supérieure, Paris, France), INRIA Rocquencourt (Institut national de recherche en informatique, France).
Toplevel
Types
Construction
val zero : t
The number 0.
val one : t
The number 1.
val minus_one : t
The number -1.
val of_int : int -> t
Converts from a base integer.
val of_int32 : int32 -> t
Converts from a 32-bit integer.
val of_int64 : int64 -> t
Converts from a 64-bit integer.
val of_nativeint : nativeint -> t
Converts from a native integer.
val of_float : float -> t
Converts from a floating-point value. The value is truncated (rounded towards zero). Raises
Overflow
on infinity and NaN arguments.
val of_string : string -> t
Converts a string to an integer. An optional
-
prefix indicates a negative number, while a+
prefix is ignored. An optional prefix0x
,0o
, or0b
(following the optional-
or+
prefix) indicates that the number is, represented, in hexadecimal, octal, or binary, respectively. Otherwise, base 10 is assumed. (Unlike C, a lone0
prefix does not denote octal.) Raises anInvalid_argument
exception if the string is not a syntactically correct representation of an integer.
val of_substring : string -> pos:int -> len:int -> t
of_substring s ~pos ~len
is the same asof_string (String.sub s pos len)
val of_string_base : int -> string -> t
Parses a number represented as a string in the specified base, with optional
-
or+
prefix. The base must be between 2 and 16.
val of_substring_base : int -> string -> pos:int -> len:int -> t
of_substring_base base s ~pos ~len
is the same asof_string_base base (String.sub s pos len)
Basic arithmetic operations
val div : t -> t -> t
Integer division. The result is truncated towards zero and obeys the rule of signs. Raises
Division_by_zero
if the divisor (second argument) is 0.
val rem : t -> t -> t
Integer remainder. Can raise a
Division_by_zero
. The result ofrem a b
has the sign ofa
, and its absolute value is strictly smaller than the absolute value ofb
. The result satisfies the equalitya = b * div a b + rem a b
.
val div_rem : t -> t -> t * t
Computes both the integer quotient and the remainder.
div_rem a b
is equal to(div a b, rem a b)
. RaisesDivision_by_zero
ifb = 0
.
val cdiv : t -> t -> t
Integer division with rounding towards +oo (ceiling). Can raise a
Division_by_zero
.
val fdiv : t -> t -> t
Integer division with rounding towards -oo (floor). Can raise a
Division_by_zero
.
val ediv_rem : t -> t -> t * t
Euclidean division and remainder.
ediv_rem a b
returns a pair(q, r)
such thata = b * q + r
and0 <= r < |b|
. RaisesDivision_by_zero
ifb = 0
.
val ediv : t -> t -> t
Euclidean division.
ediv a b
is equal tofst (ediv_rem a b)
. The result satisfies0 <= a - b * ediv a b < |b|
. RaisesDivision_by_zero
ifb = 0
.
val erem : t -> t -> t
Euclidean remainder.
erem a b
is equal tosnd (ediv_rem a b)
. The result satisfies0 <= erem a b < |b|
anda = b * ediv a b + erem a b
. RaisesDivision_by_zero
ifb = 0
.
val divexact : t -> t -> t
divexact a b
dividesa
byb
, only producing correct result when the division is exact, i.e., whenb
evenly dividesa
. It should be faster than general division. Can raise aDivision_by_zero
.
Bit-level operations
val shift_left : t -> int -> t
Shifts to the left. Equivalent to a multiplication by a power of 2. The second argument must be nonnegative.
val shift_right : t -> int -> t
Shifts to the right. This is an arithmetic shift, equivalent to a division by a power of 2 with rounding towards -oo. The second argument must be nonnegative.
val shift_right_trunc : t -> int -> t
Shifts to the right, rounding towards 0. This is equivalent to a division by a power of 2, with truncation. The second argument must be nonnegative.
val numbits : t -> int
Returns the number of significant bits in the given number. If
x
is zero,numbits x
returns 0. Otherwise,numbits x
returns a positive integern
such that2^{n-1} <= |x| < 2^n
. Note thatnumbits
is defined for negative arguments, and thatnumbits (-x) = numbits x
.
val trailing_zeros : t -> int
Returns the number of trailing 0 bits in the given number. If
x
is zero,trailing_zeros x
returnsmax_int
. Otherwise,trailing_zeros x
returns a nonnegative integern
which is the largestn
such that2^n
dividesx
evenly. Note thattrailing_zeros
is defined for negative arguments, and thattrailing_zeros (-x) = trailing_zeros x
.
val testbit : t -> int -> bool
testbit x n
return the value of bit numbern
inx
:true
if the bit is 1,false
if the bit is 0. Bits are numbered from 0. RaiseInvalid_argument
ifn
is negative.
val popcount : t -> int
Counts the number of bits set. Raises
Overflow
for negative arguments, as those have an infinite number of bits set.
Conversions
val to_int : t -> int
Converts to a base integer. May raise
Overflow
.
val to_int32 : t -> int32
Converts to a 32-bit integer. May raise
Overflow
.
val to_int64 : t -> int64
Converts to a 64-bit integer. May raise
Overflow
.
val to_nativeint : t -> nativeint
Converts to a native integer. May raise
Overflow
.
val to_float : t -> float
Converts to a floating-point value. This function rounds the given integer according to the current rounding mode of the processor. In default mode, it returns the floating-point number nearest to the given integer, breaking ties by rounding to even.
val to_string : t -> string
Gives a human-readable, decimal string representation of the argument.
val format : string -> t -> string
Gives a string representation of the argument in the specified printf-like format. The general specification has the following form:
% [flags] [width] type
Where the type actually indicates the base:
i
,d
,u
: decimalb
: binaryo
: octalx
: lowercase hexadecimalX
: uppercase hexadecimal
Supported flags are:
+
: prefix positive numbers with a+
sign- space: prefix positive numbers with a space
-
: left-justify (default is right justification)0
: pad with zeroes (instead of spaces)#
: alternate formatting (actually, simply output a literal-like prefix:0x
,0b
,0o
)
Unlike the classic
printf
, all numbers are signed (even hexadecimal ones), there is no precision field, and characters that are not part of the format are simply ignored (and not copied in the output).
val fits_int : t -> bool
Whether the argument fits in a regular
int
.
val fits_int32 : t -> bool
Whether the argument fits in an
int32
.
val fits_int64 : t -> bool
Whether the argument fits in an
int64
.
val fits_nativeint : t -> bool
Whether the argument fits in a
nativeint
.
Printing
val print : t -> unit
Prints the argument on the standard output.
val output : Stdlib.out_channel -> t -> unit
Prints the argument on the specified channel. Also intended to be used as
%a
format printer inPrintf.printf
.
val sprint : unit -> t -> string
To be used as
%a
format printer inPrintf.sprintf
.
val bprint : Stdlib.Buffer.t -> t -> unit
To be used as
%a
format printer inPrintf.bprintf
.
val pp_print : Stdlib.Format.formatter -> t -> unit
Prints the argument on the specified formatter. Can be used as
%a
format printer inFormat.printf
and as argument to#install_printer
in the top-level.
Ordering
val compare : t -> t -> int
Comparison.
compare x y
returns 0 ifx
equalsy
, -1 ifx
is smaller thany
, and 1 ifx
is greater thany
.Note that Pervasive.compare can be used to compare reliably two integers only on OCaml 3.12.1 and later versions.
val sign : t -> int
Returns -1, 0, or 1 when the argument is respectively negative, null, or positive.
val is_even : t -> bool
Returns true if the argument is even (divisible by 2), false if odd.
val is_odd : t -> bool
Returns true if the argument is odd, false if even.
Elementary number theory
val gcd : t -> t -> t
Greatest common divisor. The result is always nonnegative. We have
gcd(a,0) = gcd(0,a) = abs(a)
, includinggcd(0,0) = 0
.
val gcdext : t -> t -> t * t * t
gcdext u v
returns(g,s,t)
whereg
is the greatest common divisor andg=us+vt
.g
is always nonnegative.Note: the function is based on the GMP
mpn_gcdext
function. The exact choice ofs
andt
such thatg=us+vt
is not specified, as it may vary from a version of GMP to another (it has changed notably in GMP 4.3.0 and 4.3.1).
val lcm : t -> t -> t
Least common multiple. The result is always nonnegative. We have
lcm(a,0) = lcm(0,a) = 0
.
val powm : t -> t -> t -> t
powm base exp mod
computesbase
^exp
modulomod
. Negativeexp
are supported, in which case (base
^-1)^(-exp
) modulomod
is computed. However, ifexp
is negative butbase
has no inverse modulomod
, then aDivision_by_zero
is raised.
val powm_sec : t -> t -> t -> t
powm_sec base exp mod
computesbase
^exp
modulomod
. UnlikeZ.powm
, this function is designed to take the same time and have the same cache access patterns for any two same-size arguments. Used in cryptographic applications, it provides better resistance to side-channel attacks thanZ.powm
. The exponentexp
must be positive, and the modulusmod
must be odd. Otherwise,Invalid_arg
is raised.
val invert : t -> t -> t
invert base mod
returns the inverse ofbase
modulomod
. Raises aDivision_by_zero
ifbase
is not invertible modulomod
.
val probab_prime : t -> int -> int
probab_prime x r
returns 0 ifx
is definitely composite, 1 ifx
is probably prime, and 2 ifx
is definitely prime. Ther
argument controls how many Miller-Rabin probabilistic primality tests are performed (5 to 10 is a reasonable value).
val nextprime : t -> t
Returns the next prime greater than the argument. The result is only prime with very high probability.
val remove : t -> t -> t * int
remove a b
returnsa
after removing all the occurences of the factorb
. Also returns how many occurrences were removed.
val fac : int -> t
fac n
returns the factorial ofn
(n!
). Raises anInvaid_argument
ifn
is non-positive.
val fac2 : int -> t
fac2 n
returns the double factorial ofn
(n!!
). Raises anInvaid_argument
ifn
is non-positive.
val facM : int -> int -> t
facM n m
returns them
-th factorial ofn
. Raises anInvaid_argument
ifn
orm
is non-positive.
val primorial : int -> t
primorial n
returns the product of all positive prime numbers less than or equal ton
. Raises anInvaid_argument
ifn
is non-positive.
val bin : t -> int -> t
bin n k
returns the binomial coefficientn
overk
. Raises anInvaid_argument
ifk
is non-positive.
val fib : int -> t
fib n
returns then
-th Fibonacci number. Raises anInvaid_argument
ifn
is non-positive.
val lucnum : int -> t
lucnum n
returns then
-th Lucas number. Raises anInvaid_argument
ifn
is non-positive.
Powers
val pow : t -> int -> t
pow base exp
raisesbase
to theexp
power.exp
must be nonnegative. Note that only exponents fitting in a machine integer are supported, as larger exponents would surely make the result's size overflow the address space.
val sqrt : t -> t
Returns the square root. The result is truncated (rounded down to an integer). Raises an
Invalid_argument
on negative arguments.
val sqrt_rem : t -> t * t
Returns the square root truncated, and the remainder. Raises an
Invalid_argument
on negative arguments.
val root : t -> int -> t
root x n
computes then
-th root ofx
.n
must be positive and, ifn
is even, thenx
must be nonnegative. Otherwise, anInvalid_argument
is raised.
val rootrem : t -> int -> t * t
rootrem x n
computes then
-th root ofx
and the remainderx-root**n
.n
must be positive and, ifn
is even, thenx
must be nonnegative. Otherwise, anInvalid_argument
is raised.
val perfect_power : t -> bool
True if the argument has the form
a^b
, withb>1
val perfect_square : t -> bool
True if the argument has the form
a^2
.
val log2 : t -> int
Returns the base-2 logarithm of its argument, rounded down to an integer. If
x
is positive,log2 x
returns the largestn
such that2^n <= x
. Ifx
is negative or zero,log2 x
raise theInvalid_argument
exception.
val log2up : t -> int
Returns the base-2 logarithm of its argument, rounded up to an integer. If
x
is positive,log2up x
returns the smallestn
such thatx <= 2^n
. Ifx
is negative or zero,log2up x
raise theInvalid_argument
exception.
Representation
val size : t -> int
Returns the number of machine words used to represent the number.
val extract : t -> int -> int -> t
extract a off len
returns a nonnegative number corresponding to bitsoff
tooff
+len
-1 ofb
. Negativea
are considered in infinite-length 2's complement representation.
val signed_extract : t -> int -> int -> t
signed_extract a off len
extracts bitsoff
tooff
+len
-1 ofb
, asextract
does, then sign-extends bitlen-1
of the result (that is, bitoff + len - 1
ofa
). The result is between- 2{^[len]-1}
(included) and2{^[len]-1}
(excluded), and equal toextract a off len
modulo2{^len}
.
val to_bits : t -> string
Returns a binary representation of the argument. The string result should be interpreted as a sequence of bytes, corresponding to the binary representation of the absolute value of the argument in little endian ordering. The sign is not stored in the string.
val of_bits : string -> t
Constructs a number from a binary string representation. The string is interpreted as a sequence of bytes in little endian order, and the result is always positive. We have the identity:
of_bits (to_bits x) = abs x
. However, we can haveto_bits (of_bits s) <> s
due to the presence of trailing zeros in s.
Prefix and infix operators
val (~$) : int -> t
Conversion from
int
of_int
.
module Compare : sig ... end