# NAME

Math::AnyNum - Arbitrary size precision for integers, rationals, floating-points and complex numbers.

Version 0.40

# SYNOPSIS

Math::AnyNum provides a transparent and easy-to-use interface to Math::GMPz, Math::GMPq, Math::MPFR and Math::MPC, along with a decent number of useful mathematical functions.

``````    use 5.016;

# Integers
say factorial(30);              #=> 265252859812191058636308480000000

# Floating-point numbers
say sqrt(1 / factorial(100));   #=> 1.0351378111756264713204945[...]e-79

# Rational numbers
my \$x = 2/3;
say (\$x * 3);                   #=> 2
say (2 / \$x);                   #=> 3
say \$x;                         #=> 2/3

# Complex numbers
say 3 + 4*i;                    #=> 3+4i
say sqrt(-4);                   #=> 2i
say log(-1);                    #=> 3.1415926535897932384626433832[...]i``````

# DESCRIPTION

Math::AnyNum focuses primarily on providing a friendly interface and good performance. In most cases, it can be used as a drop-in replacement for the bignum and bigrat pragmas.

The philosophy of Math::AnyNum is that mathematics should just work, therefore the support for complex numbers is virtually transparent, without requiring any explicit conversions. All the conversions are done implicitly, using a fairly sophisticated promotion system, which tries really hard to do the right thing and as efficiently as possible.

Additionally, each Math::AnyNum object is immutable.

# FUNCTIONS

``````  :ntheory

binomial(n,k)             binomial coefficient
multinomial(@list)        multinomial coefficient
factorial(n)              product of first n positive integers: n!
dfactorial(n)             double-factorial: n!!
mfactorial(n,k)           multi-factorial: n*(n-k)*(n-2k)*...
subfactorial(n)           number of derangements: !n
subfactorial(n,k)         number of derangements with k fixed points
superfactorial(n)         product of first n factorials
hyperfactorial(n)         product of k^k for k=1..n
rising_factorial(n,k)     rising factorial: n^(k)
falling_factorial(n,k)    falling factorial: (n)_k
bell(n)                   n-th Bell number
catalan(n)                n-th Catalan number
catalan(n,k)              C(n,k) entry in Catalan's triangle
lucas(n)                  n-th Lucas number
lucasmod(n,m)             n-th Lucas number modulo m
lucasU(P,Q,n)             Lucas U_n(P, Q) function
lucasV(P,Q,n)             Lucas V_n(P, Q) function
lucasUmod(P,Q,n,m)        Lucas U_n(P, Q) modulo m
lucasVmod(P,Q,n,m)        Lucas V_n(P, Q) modulo m
fibonacci(n)              n-th Fibonacci number
fibonacci(n,k)            n-th Fibonacci number of k-th order
fibmod(n,m)               n-th Fibonacci number modulo m
polygonal(n,k)            n-th k-gonal number
harmonic(n)               n-th harmonic number: 1 + 1/2 + ... + 1/n
secant_number(n)          n-th secant/zig number
tangent_number(n)         n-th tangent/zag number
euler(n)                  n-th Euler number: E_n
euler(n,x)                Euler polynomials: E_n(x)
bernoulli(n)              n-th Bernoulli number: B_n
bernoulli(n,x)            Bernoulli polynomials: B_n(x)
faulhaber(n,x)            Faulhaber polynomials: F_n(x)
laguerreL(n,x)            Laguerre polynomials: L_n(x)
legendreP(n,x)            Legendre polynomials: P_n(x)
hermiteH(n,x)             Physicists' Hermite polynomials: H_n(x)
hermiteHe(n,x)            Probabilists' Hermite polynomials: He_n(x)
chebyshevT(n,x)           Chebyshev polynomials of the 1st kind: T_n(x)
chebyshevU(n,x)           Chebyshev polynomials of the 2nd kind: U_n(x)
chebyshevTmod(n,x,m)      Modular Chebyshev polynomials of the 1st kind: T_n(x)
chebyshevUmod(n,x,m)      Modular Chebyshev polynomials of the 2nd kind: U_n(x)
faulhaber_sum(n,k)        sum of powers: 1^k + 2^k + ... + n^k
geometric_sum(n,r)        geometric sum: r^0 + r^1 + ... + r^n
dirichlet_sum(n,f,g,F,G)  Dirichlet hyperbola method
kronecker(n,k)            Kronecker (Jacobi) symbol
lcm(@list)                least common multiple
gcd(@list)                greatest common divisor
gcdext(n,k)               return (u,v,d) where u*n+v*k=d
isub(a,b)                 integer subtraction: a-b
imul(a,b)                 integer multiplication: a*b
idiv(a,b)                 floor division: floor(a/b)
idiv_ceil(a,b)            ceil division: int(a/b)
idiv_round(a,b)           round division: int(a/b)
idiv_trunc(a,b)           truncated division: trunc(a/b)
imod(a,b)                 integer remainder: a%b
ipow(n,k)                 integer exponentiation: n^k
ipow2(k)                  integer exponentiation: 2^k
ipow10(k)                 integer exponentiation: 10^k
iroot(n,k)                integer k-th root of n
isqrt(n)                  integer square root of n
icbrt(n)                  integer cube root of n
ilog(n,k)                 integer logarithm of n to base k
ilog2(n)                  integer logarithm of n to base 2
ilog10(n)                 integer logarithm of n to base 10
submod(a,b,m)             modular integer subtraction: (a-b)%m
mulmod(a,b,m)             modular integer multiplication: (a*b)%m
divmod(a,b,m)             modular integer division: (a/b)%m
divmod(a,b)               quotient and remainder of a/b
invmod(n,m)               multiplicative inverse of n modulo m
powmod(a,b,m)             modular exponentiation: a ^ b mod m
isqrtrem(n)               integer sqrt remainder: n - isqrt(n)^2
irootrem(n,k)             integer root remainder: n - iroot(n,k)^k
is_square(n)              return 1 if n is a perfect square
is_power(n)               return 1 if n = c^k for integers c, k > 1
is_power(n,k)             return 1 if n = c^k for integers c, k
is_polygonal(n,k)         return 1 if n is a first k-gonal number
is_polygonal2(n,k)        return 1 if n is a second k-gonal number
is_coprime(n,k)           return 1 if gcd(n,k) = 1
is_rough(n,B)             return 1 if all prime factors of n are >= B
is_smooth(n,B)            return 1 if all prime factors of n are <= B
is_smooth_over_prod(n,k)  return 1 if n is smooth over the primes p|k
rough_part(n,B)           largest B-rough divisor of n
smooth_part(n,B)          largest B-smooth divisor of n
make_coprime(n,k)         largest divisor of n coprime to k
is_prime(n,r=23)          Miller-Rabin primality test
primorial(n)              product of primes <= n
next_prime(n)             next prime > n
valuation(n,k)            number of times n is divisible by k
remdiv(n,k)               n / k^valuation(n,k)
ipolygonal_root(n,k)      first integer k-gonal root of n
ipolygonal_root2(n,k)     second integer k-gonal root of n

:special

beta(x,y)                    Beta function
eta(x)                       Dirichlet eta function η(x)
gamma(x)                     Gamma function Γ(x)
lgamma(x)                    natural logarithm of abs(Γ(x))
lngamma(x)                   natural logarithm of Γ(x)
lnsuperfactorial(n)          natural logarithm of superfactorial(n)
lnhyperfactorial(n)          natural logarithm of hyperfactorial(n)
digamma(x)                   Digamma function ψ(x)
zeta(x)                      Zeta function ζ(x)
Ai(x)                        Airy function
Ei(x)                        exponential integral function
Li(x)                        logarithmic integral function
Li2(x)                       dilogarithm function
lgrt(x)                      logarithmic-root: lgrt(x^x) = x
LambertW(x)                  Lambert W function
BesselJ(x,n)                 first order Bessel function J_n(x)
BesselY(x,n)                 second order Bessel function Y_n(x)
pow(x,y)                     power function: x^y
sqr(x)                       square function: x^2
sqrt(x)                      square root function: x^(1/2)
cbrt(x)                      cube root function: x^(1/3)
root(x,y)                    root function: x^(1/y)
exp(x)                       exponential function: e^x
exp2(x)                      exponential function: 2^x
exp10(x)                     exponential function: 10^x
ln(x)                        natural logarithm of x
log(x,y)                     logarithm of x to base y
log2(x)                      logarithm of x to base 2
log10(x)                     logarithm of x to base 10
mod(x,y)                     remainder of x/y
polymod(n,@list)             n modulo a list of numbers
erf(x)                       the Gauss error function
erfc(x)                      the complementary error function
abs(x)                       absolute value of x
agm(x,y)                     arithmetic-geometric mean
hypot(x,y)                   hypotenuse: sqrt(x^2 + y^2)
norm(x)                      normalized value of x: abs(x)^2
lnbern(n)                    natural logarithm of bernoulli(n)
bernreal(n)                  Bernoulli number as floating-point
harmreal(n)                  Harmonic number as floating-point
polygonal_root(n,k)          first k-gonal root of n
polygonal_root2(n,k)         second k-gonal root of n

:trig

sin(x)              trigonometric sine function
cos(x)              trigonometric cosine function
tan(x)              trigonometric tangent function
csc(x)              trigonometric cosecant function
sec(x)              trigonometric secant function
cot(x)              trigonometric cotangent function

asin(x)             inverse of trigonometric sine
acos(x)             inverse of trigonometric cosine
atan(x)             inverse of trigonometric tangent
acsc(x)             inverse of trigonometric cosecant
asec(x)             inverse of trigonometric secant
acot(x)             inverse of trigonometric cotangent

sinh(x)             hyperbolic sine function
cosh(x)             hyperbolic cosine function
tanh(x)             hyperbolic tangent function
csch(x)             hyperbolic cosecant function
sech(x)             hyperbolic secant function
coth(x)             hyperbolic cotangent function

asinh(x)            inverse of hyperbolic sine
acosh(x)            inverse of hyperbolic cosine function
atanh(x)            inverse of hyperbolic tangent
acsch(x)            inverse of hyperbolic cosecant
asech(x)            inverse of hyperbolic secant
acoth(x)            inverse of hyperbolic cotangent

atan2(x,y)          two-argument variant of arctangent

:misc

rand(a)             pseudorandom floating-point: 0 <= R < a
rand(a,b)           pseudorandom floating-point: a <= R < b
irand(a)            pseudorandom integer: 0 <= R <= a
irand(a,b)          pseudorandom integer: a <= R <= b
seed(n)             re-seed the `rand()` function
iseed(n)            re-seed the `irand()` function
int(x)              truncate x to an integer
floor(x)            round x towards -Infinity
ceil(x)             round x towards +Infinity
round(x)            round x to the nearest integer
round(x,+k)         round x to k places before the decimal point
round(x,-k)         round x to k places after the decimal point
acmp(a,b)           absolute comparison: abs(a) <=> abs(b)
approx_cmp(a,b,k)   approximate comparison: round(a,k) <=> round(b,k)
rat(x)              convert x to a rational number
rat(str)            parse a decimal expansion as an exact fraction
rat_approx(x)       rational approximation of a real number x
ratmod(r,m)         rational modular operation as an integer: r % m
numerator(r)        numerator of rational number r
denominator(r)      denominator of rational number r
nude(r)             numerator and denominator of r
float(x)            convert x to a floating-point number
complex(x)          convert x to a floating-point complex number
complex(a,b)        complex number: a + b*i
real(z)             real part of complex number z
imag(z)             imaginary part of complex number z
reals(z)            real and imaginary part of z as reals
sgn(x)              -1 if x < 0; 0 if x = 0; 1 if x > 0
neg(x)              additive inverse of x: -x
inv(x)              multiplicative inverse of x: 1/x
conj(x)             complex conjugate of x
digits(n,b)         digits of n in base b
digits2num(\@d,b)   conversion of digits in base b to an integer
sumdigits(n,b)      sum of digits of n in base b
popcount(n)         number of 1's in binary representation of n
hamdist(n,k)        number of bit-positions where the bits differ
getbit(n,k)         k-th bit of integer n (1 or 0)
setbit(n,k)         set the k-th bit of integer n to 1
clearbit(n,k)       set the k-th bit of integer n to 0
flipbit(n,k)        flip the k-th bit of integer n
bit_scan0(n,k)      index of the first 0-bit of n with index >= k
bit_scan1(n,k)      index of the first 1-bit of n with index >= k

min(@list)          minimum value from a given list of numbers
max(@list)          maximum value from a given list of numbers

sum(@list)          sum of a list of numbers
prod(@list)         product of a list of numbers

bsearch(n,\&f)      binary search from 0 to n (exact match)
bsearch(a,b,\&f)    binary search from a to b (exact match)
bsearch_le(n,\&f)   binary search from 0 to n (less than or equal to)
bsearch_le(a,b,\&f) binary search from a to b (less than or equal to)
bsearch_ge(n,\&f)   binary search from 0 to n (greater than or equal to)
bsearch_ge(a,b,\&f) binary search from a to b (greater than or equal to)

base(n,b)           string-representation of n in base b
as_bin(n)           binary string-representation of n
as_oct(n)           octal string-representation of n
as_int(n,b)         integer string-representation of n in base b
as_rat(n,b)         rational string-representation of n in base b
as_frac(n,b)        fraction string-representation of n in base b
as_dec(n,d)         decimal string-expansion of n with d digits

is_pos(n)           return 1 if n > 0
is_neg(n)           return 1 if n < 0
is_int(n)           return 1 if n is an integer
is_rat(n)           return 1 if n is a rational number
is_real(n)          return 1 if n is a real number
is_imag(n)          return 1 if n is an imaginary number
is_complex(n)       return 1 if n is a complex number
is_inf(n)           return 1 if n is +Infinity
is_ninf(n)          return 1 if n is -Infinity
is_nan(n)           return 1 if n is Not-a-Number (NaN)
is_zero(n)          return 1 if n = 0
is_one(n)           return 1 if n = 1
is_mone(n)          return 1 if n = -1
is_even(n)          return 1 if n is an integer divisible by 2
is_odd(n)           return 1 if n is an integer not divisible by 2
is_div(n,k)         return 1 if n is exactly divisible by k
is_congruent(n,k,m) return 1 if n is congruent to k mod m``````

# EXPORT

Each function can be exported individually, as:

``    use Math::AnyNum qw(zeta);``

There is also the possibility of exporting an entire group of functions, as:

``    use Math::AnyNum qw(:trig);``

Additionally, by specifying the `:all` keyword, will export all the exportable functions and all the constants.

``    use Math::AnyNum qw(:all);``

The `:overload` keyword enables constant overloading, which makes each number a Math::AnyNum object and also exports the `i`, `Inf` and `NaN` constants:

``````    use Math::AnyNum qw(:overload);
say 42;                                       #=> "42"   (as Int)
say 1/2;                                      #=> "1/2"  (as Rat)
say 0.5;                                      #=> "0.5"  (as Float)
say 3 + 4*i;                                  #=> "3+4i" (as Complex)``````

NOTE: `:overload` is lexical to the current scope only.

The syntax for disabling the `:overload` behavior in the current scope, is:

``    no Math::AnyNum;        # :overload will be disabled in the current scope``

In addition to the exportable functions, Math::AnyNum also provides a list with useful mathematical constants that can be exported, such as:

``````    i           # imaginary unit             sqrt(-1)
e           # e mathematical constant    2.718281828459...
pi          # PI constant                3.141592653589...
tau         # TAU constant               6.283185307179...
ln2         # natural logarithm of 2     0.693147180559...
phi         # golden ratio               1.618033988749...
EulerGamma  # Euler-Mascheroni constant  0.577215664901...
CatalanG    # Catalan G constant         0.915965594177...
Inf         # positive Infinity
NaN         # Not-a-Number``````

The syntax for exporting a constant, is:

``````    use Math::AnyNum qw(pi);
say pi;                          # 3.141592653589...``````

Nothing is exported by default.

# HOW IT WORKS

Internally, each Math::AnyNum object holds a reference to an object of type Math::GMPz, Math::GMPq, Math::MPFR or Math::MPC. Based on the internal types, it decides what functions to call on each operation and does automatic promotion whenever is necessary.

The promotion rules can be summarized as follows:

``````    (Integer, Integer)   -> Integer  | Rational | Float   | Complex
(Integer, Rational)  -> Rational | Float    | Complex
(Integer, Float)     -> Float    | Complex
(Integer, Complex)   -> Complex

(Rational, Rational) -> Rational | Float    | Complex
(Rational, Float)    -> Float    | Complex
(Rational, Complex)  -> Complex

(Float, Float)       -> Float    | Complex
(Float, Complex)     -> Complex

(Complex, Complex)   -> Complex``````

For explicit conversions, Math::AnyNum provides the following functions:

``````    int(x)          # converts x to an integer (NaN if not possible)
rat(x)          # converts x to a rational (NaN if not possible)
float(x)        # converts x to a real or complex floating-point number
complex(x)      # converts x to a complex floating-point number``````

# PRECISION

The default precision for floating-point numbers is 192 bits, which is equivalent with about 50 digits of precision in base 10.

The precision can be changed by modifying the `\$Math::AnyNum::PREC` variable, such as:

``    local \$Math::AnyNum::PREC = 1024;``

or by specifying the precision at import (this sets the precision globally):

``    use Math::AnyNum PREC => 1024;``

This precision is used internally whenever a `Math::MPFR` or a `Math::MPC` object is created.

For example, if we change the precision to 3 decimal digits (where `4` is the conversion factor), we get the following results:

``````    local \$Math::AnyNum::PREC = 3*4;

# Floating-points
say sqrt(2);                                  #=> 1.41
say sqrt(19+13*i);                            #=> 4.58+1.42i

# Integers
say 98**7;                                    #=> 86812553324672

# Rationals
say 1 / 98**7                                 #=> 1/86812553324672``````

Notice that integers and rational numbers do not obey this precision, because they can grow and shrink dynamically, without a specific limit.

Furthermore, a rational number never losses precision or accuracy in rational operations, therefore if we say:

``````    my \$x = 1/3;
say \$x*3;                                     #=> 1
say 1/\$x;                                     #=> 3
say 3/\$x;                                     #=> 9``````

...the results are exact.

# NOTATIONS

Methods that begin with an i followed by the actual name (e.g.: `isqrt`), do integer operations, by first truncating their arguments to integers, if necessary.

The returned types are noted as follows:

``````    Any         # any type of number
Int         # an integer value
Rat         # a rational value
Float       # a floating-point value
Complex     # a floating-point complex value
NaN         # "Not-a-Number" value
Inf         # +/-Infinity
Bool        # a Boolean value (1 or 0)
Scalar      # a Perl scalar``````

When two or more types are separated with pipe characters (|), it means that the corresponding function can return any of the specified types.

# INITIALIZATION / CONSTANTS

This section includes methods for creating new Math::AnyNum objects and some useful mathematical constants.

## new

``````    Math::AnyNum->new(n)                          #=> Any
Math::AnyNum->new(n, base)                    #=> Any``````

Returns a new AnyNum object with the value specified in the first argument, which can be a Perl numerical value, a string representing a number in a rational form, such as `"1/2"`, a string holding a decimal expansion number, such as `"0.5"`, a string holding an integer, such as `"255"` or a string holding a complex number, such as `"3+4i"` or `"(3 4)"`.

``````    my \$z = Math::AnyNum->new('42');        # integer
my \$r = Math::AnyNum->new('3/4');       # rational
my \$f = Math::AnyNum->new('12.34');     # float
my \$c = Math::AnyNum->new('3.1+4i');    # complex``````

The second argument specifies the base of the number, which must be between 2 and 62.

When no base is specified, it defaults to base 10.

For setting an hexadecimal number, we can say:

``    my \$n = Math::AnyNum->new("deadbeef", 16);``

NOTE: no prefix, such as `"0x"` or `"0b"`, is allowed as part of the number.

## new_si

``    Math::AnyNum->new_si(n)                       #=> Int``

Sets a signed native integer.

Example:

``    my \$n = Math::AnyNum->new_si(-42);``

## new_ui

``    Math::AnyNum->new_ui(n)                       #=> Int``

Sets an unsigned native integer.

Example:

``    my \$n = Math::AnyNum->new_ui(42);``

## new_z

``````    Math::AnyNum->new_z(str)                      #=> Int
Math::AnyNum->new_z(str, base)                #=> Int``````

Sets an arbitrary large integer from a given string.

The second argument specifies the base of the number, which must be between 2 and 62.

When no base is specified, it defaults to base 10.

Example:

``````    my \$n = Math::AnyNum->new_z("12345678910111213141516");
my \$m = Math::AnyNum->new_z("fffffffffffffffffff", 16);``````

## new_q

``````    Math::AnyNum->new_q(frac)                     #=> Rat
Math::AnyNum->new_q(num, den)                 #=> Rat
Math::AnyNum->new_q(num, den, base)           #=> Rat``````

Sets an arbitrary large rational from a given string.

The third argument specifies the base of the number, which must be between 2 and 62.

When no base is specified, it defaults to base 10.

Example:

``````    my \$n = Math::AnyNum->new_q('12345/67890');         # 823/4526
my \$m = Math::AnyNum->new_q('12345', '67890');      # 823/4526
my \$o = Math::AnyNum->new_q('fffff', 'aaaaa', 16);  # 1048575/699050 = 3/2``````

## new_f

``````    Math::AnyNum->new_f(str)                      #=> Float
Math::AnyNum->new_f(str, base)                #=> Float``````

Sets a floating-point real number from a given string.

The second argument specifies the base of the number, which must be between 2 and 62.

When no base is specified, it defaults to base 10.

Example:

``````    my \$n = Math::AnyNum->new_f('12.345');          # 12.345
my \$m = Math::AnyNum->new_f('-1.2345e-12');     # -0.0000000000012345
my \$o = Math::AnyNum->new_f('ffffff', 16);      # 16777215``````

## new_c

``````    Math::AnyNum->new_c(real)                     #=> Complex
Math::AnyNum->new_c(real, imag)               #=> Complex
Math::AnyNum->new_c(real, imag, base)         #=> Complex``````

Sets a complex number from a given string.

The third argument specifies the base of the number, which must be between 2 and 62.

When no base is specified, it defaults to base 10.

Example:

``````    my \$n = Math::AnyNum->new_c('1.123');           # 1.123
my \$m = Math::AnyNum->new_c('3', '4');          # 3+4i
my \$o = Math::AnyNum->new_c('f', 'a', 16);      # 15+10i``````

## nan

``    Math::AnyNum->nan                             #=> NaN``

Returns an object holding the `NaN` value.

## inf

``    Math::AnyNum->inf                             #=> Inf``

Returns an object representing positive infinity.

## ninf

``    Math::AnyNum->ninf                            #=> -Inf``

Returns an object representing negative infinity.

## one

``    Math::AnyNum->one                             #=> Int``

Returns an object containing the value `1`.

## mone

``    Math::AnyNum->mone                            #=> Int``

Returns an object containing the value `-1`.

## zero

``    Math::AnyNum->zero                            #=> Int``

Returns an object containing the value `0`.

## i

``    Math::AnyNum->i                               #=> Complex``

Returns the imaginary unit, which is `sqrt(-1)`.

## e

``    Math::AnyNum->e                               #=> Float``

Returns the e mathematical constant, which is `2.718...`.

## pi

``    Math::AnyNum->pi                              #=> Float``

Returns the number PI, which is `3.1415...`.

## tau

``    Math::AnyNum->tau                             #=> Float``

Returns the number TAU, which is `2*pi`.

## ln2

``    Math::AnyNum->ln2                             #=> Float``

Returns the natural logarithm of `2`.

## phi

``    Math::AnyNum->phi                             #=> Float``

Returns the value of the golden ratio, which is `1.61803...`.

## EulerGamma

``    Math::AnyNum->EulerGamma                      #=> Float``

Returns the Euler-Mascheroni γ constant, which is `0.57721...`.

## CatalanG

``    Math::AnyNum->CatalanG                        #=> Float``

Returns the Catalan G constant, also known as `Beta(2)`, which is `0.91596...`.

# ARITHMETIC OPERATIONS

This section includes basic arithmetic operations.

``    x + y                                         #=> Any``

Adds `x` and `y` and returns the result.

## sub

``    x - y                                         #=> Any``

Subtracts `y` from `x` and returns the result.

## mul

``    x * y                                         #=> Any``

Multiplies `x` by `y` and returns the result.

## div

``    x / y                                         #=> Any``

Divides `x` by `y` and returns the result.

## mod

``````    x % y                                         #=> Any
mod(x, y)                                     #=> Any``````

Remainder of `x` when is divided by `y`. Returns NaN when `y` is zero.

Implemented as:

``    x % y = x - y*floor(x/y)``

## polymod

``    polymod(n, a, b, c, ...)                      #=> (Any, Any, ..., Any)``

Returns a list of mod results corresponding to the divisors in `(a, b, c, ...)`. The divisors are given from smallest "unit" to the largest (e.g. 60 seconds per minute, 60 minutes per hour) and the results are returned in the same way: from smallest to the largest (5 seconds, 4 minutes).

Example:

``    my (\$s, \$m, \$h, \$d) = polymod(\$seconds, 60, 60, 24);``

## conj

``    conj(x)                                       #=> Float | Complex``

Complex conjugate of `x`. Returns `x` when `x` is a real number.

Example:

``    conj("3+4i") = 3-4*i``

## inv

``    inv(x)                                        #=> Any``

Multiplicative inverse of `x`. Equivalent with `1/x`.

## neg

``    neg(x)                                        #=> Any``

Additive inverse of `x`. Equivalent with `-x`.

## abs

``    abs(x)                                        #=> Any``

Absolute value of `x`.

## sqr

``    sqr(x)                                        #=> Any``

Multiplies `x` with itself and returns the result. Equivalent with `x*x`.

## norm

``    norm(x)                                       #=> Any``

The square of the absolute value of `x`. Equivalent with `abs(x)**2`.

# SPECIAL FUNCTIONS

This section includes the special functions.

## sqrt

``    sqrt(x)                                       #=> Float | Complex``

Square root of `x`. Returns a complex number when `x` is negative.

## cbrt

``    cbrt(x)                                       #=> Float | Complex``

Cube root of `x`. Returns a complex number when `x` is negative.

## root

``    root(x, y)                                    #=> Float | Complex``

The `y` root of `x`. Equivalent with `x**(1/y)`.

## polygonal_root

``    polygonal_root(n, k)                          #=> Float | Complex``

Returns the k-gonal root of `n`. Also defined for complex numbers.

Example:

``````    say polygonal_root(\$n, 3);      # triangular root
say polygonal_root(\$n, 5);      # pentagonal root``````

## polygonal_root2

``    polygonal_root2(n, k)                         #=> Float | Complex``

Returns the second k-gonal root of `n`. Also defined for complex numbers.

Example:

``    say polygonal_root2(\$n, 5);      # second pentagonal root``

## pow

``````    x ** y                                        #=> Any
pow(x, y)                                     #=> Any``````

Raises `x` to power `y` and returns the result.

When `x` and `y` are both integers, it does integer exponentiation and returns the exact result.

When `x` is rational and `y` is an integer, it does rational exponentiation based on the identity: `(a/b)**n = a**n / b**n`, which also computes the exact result.

Otherwise, it does floating-point exponentiation, which is equivalent with `exp(log(x) * y)`.

## exp

``    exp(x)                                        #=> Float | Complex``

Natural exponentiation of `x` (i.e.: `e**x`).

## exp2

``    exp2(x)                                       #=> Any``

Raises 2 to the power `x`. (i.e.: `2**x`)

## exp10

``    exp10(x)                                      #=> Any``

Raises 10 to the power `x`. (i.e.: `10**x`)

## ln | log

``````    ln(x)                                         #=> Float | Complex
log(x)                                        #=> Float | Complex
log(x, y)                                     #=> Float | Complex``````

Logarithm of `x` to base `y` (or base e when `y` is omitted).

NOTE: `log(x, y)` is equivalent with `log(x) / log(y)`.

## log2 | log10

``````    log2(x)                                       #=> Float | Complex
log10(x)                                      #=> Float | Complex``````

Logarithm of `x` to base 2 and base 10, respectively.

## lgrt

``    lgrt(x)                                       #=> Float | Complex``

Logarithmic-root of `x`, which is the solution to `a**a = x`, where `x` is known. When the value of `x` is less than `e**(-1/e)`, it returns a complex number.

It also accepts a complex number as input.

Example:

``     lgrt(100)          # solves for x in `x**x = 100` and returns: `3.59728...```

This function is related to the Lambert-W function via the following identities:

``````    log(lgrt(exp(x)))     = LambertW(x)
exp(LambertW(log(x))) = lgrt(x)``````

## LambertW

``    LambertW(x)                                   #=> Float | Complex``

The Lambert-W function. When the value of `x` is less than `-1/e`, it returns a complex number.

It also accepts a complex number as input.

Identities (assuming x>0):

``````     LambertW(exp(x)*x) = x
LambertW(log(x)*x) = log(x)``````

## bernreal

``    bernreal(n)                                   #=> Float``

Returns the n-th Bernoulli number, as a floating-point approximation, with `bernreal(1) = 0.5`.

## lnbern

``    lnbern(n)                                     #=> Float | Complex``

Returns the natural logarithm of the n-th Bernoulli number.

## harmreal

``    harmreal(n)                                   #=> Float``

Returns the n-th Harmonic number, as a floating-point approximation, for any real value of `n`.

Returns NaN for negative integers.

Defined as:

``    harmreal(n) = digamma(n+1) + γ``

where `γ` is the Euler-Mascheroni constant.

## agm

``    agm(x, y)                                     #=> Float | Complex``

Arithmetic-geometric mean of `x` and `y`. Also defined for complex numbers.

## hypot

``    hypot(x, y)                                   #=> Float | Complex``

The value of the hypotenuse for catheti `x` and `y`. Equivalent to `sqrt(x**2 + y**2)`. Also defined for complex numbers.

## gamma

``    gamma(x)                                      #=> Float``

The Gamma function on `x`. Returns Inf when `x` is zero, and NaN when `x` is a negative integer.

## lgamma

``    lgamma(x)                                     #=> Float``

Natural logarithm of the absolute value of the Gamma function.

## lngamma

``    lngamma(x)                                    #=> Float``

Natural logarithm of the Gamma function for which the logarithm is a real number. Returns NaN otherwise.

## lnsuperfactorial

``    lnsuperfactorial(n)                           #=> Float``

Natural logarithm of `superfactorial(n)`, where `n` is a non-negative integer.

## lnhyperfactorial

``    lnsuperfactorial(n)                           #=> Float``

Natural logarithm of `hyperfactorial(n)`, where `n` is a non-negative integer.

## digamma

``    digamma(x)                                    #=> Float``

The Digamma function (sometimes called Psi). Returns NaN when `x` is negative, and -Inf when `x` is 0.

## beta

``    beta(x, y)                                    #=> Float``

The beta function (also called the Euler integral of the first kind).

Defined as:

``    beta(x, y) = gamma(x)*gamma(y) / gamma(x+y)``

## zeta

``    zeta(x)                                       #=> Float``

The Riemann zeta function at `x`. Returns Inf when `x` is 1.

## eta

``    eta(x)                                        #=> Float``

The Dirichlet eta function at `x`.

Defined as:

``````    eta(1) = ln(2)
eta(x) = (1 - 2**(1-x)) * zeta(x)``````

## BesselJ

``    BesselJ(x, n)                                 #=> Float``

The first order Bessel function, `J_n(x)`, where `n` is a signed integer.

Example:

``    BesselJ(x, n)        # represents J_n(x)``

## BesselY

``    BesselY(x, n)                                 #=> Float``

The second order Bessel function, `Y_n(x)`, where `n` is a signed integer. Returns NaN for negative values of `x`.

Example:

``    BesselY(x, n)        # represents Y_n(x)``

## erf

``    erf(x)                                        #=> Float``

The error function on `x`.

## erfc

``    erfc(x)                                       #=> Float``

Complementary error function on `x`.

## Ai

``    Ai(x)                                         #=> Float``

The Airy function on `x`.

## Ei

``    Ei(x)                                         #=> Float``

Exponential integral of `x`. Returns -Inf when `x` is zero, and NaN when `x` is negative.

## Li

``    Li(x)                                         #=> Float``

The logarithmic integral of `x`, defined as: `Ei(ln(x))`. Returns -Inf when `x` is 1, and NaN when `x` is less than or equal to `0`.

## Li2

``    Li2(x)                                        #=> Float``

The dilogarithm function, defined as the integral of `-log(1-t)/t` from `0` to `x`.

# TRIGONOMETRIC FUNCTIONS

## sin | sinh | asin | asinh

``````    sin(x)                                        #=> Float | Complex
sinh(x)                                       #=> Float | Complex
asin(x)                                       #=> Float | Complex
asinh(x)                                      #=> Float | Complex``````

Sine, hyperbolic sine, inverse sine and inverse hyperbolic sine.

## cos | cosh | acos | acosh

``````    cos(x)                                        #=> Float | Complex
cosh(x)                                       #=> Float | Complex
acos(x)                                       #=> Float | Complex
acosh(x)                                      #=> Float | Complex``````

Cosine, hyperbolic cosine, inverse cosine and inverse hyperbolic cosine.

## tan | tanh | atan | atanh

``````    tan(x)                                        #=> Float | Complex
tanh(x)                                       #=> Float | Complex
atan(x)                                       #=> Float | Complex
atanh(x)                                      #=> Float | Complex``````

Tangent, hyperbolic tangent, inverse tangent and inverse hyperbolic tangent.

## cot | coth | acot | acoth

``````    cot(x)                                        #=> Float | Complex
coth(x)                                       #=> Float | Complex
acot(x)                                       #=> Float | Complex
acoth(x)                                      #=> Float | Complex``````

Cotangent, hyperbolic cotangent, inverse cotangent and inverse hyperbolic cotangent.

## sec | sech | asec | asech

``````    sec(x)                                        #=> Float | Complex
sech(x)                                       #=> Float | Complex
asec(x)                                       #=> Float | Complex
asech(x)                                      #=> Float | Complex``````

Secant, hyperbolic secant, inverse secant and inverse hyperbolic secant.

## csc | csch | acsc | acsch

``````    csc(x)                                        #=> Float | Complex
csch(x)                                       #=> Float | Complex
acsc(x)                                       #=> Float | Complex
acsch(x)                                      #=> Float | Complex``````

Cosecant, hyperbolic cosecant, inverse cosecant and inverse hyperbolic cosecant.

## atan2

``    atan2(x, y)                                   #=> Float | Complex``

The arc tangent of `x` and `y`, defined as:

``    atan2(x, y) = -i * log((y + x*i) / sqrt(x^2 + y^2))``

``    deg2rad(x)                                    #=> Float | Complex``

Returns the value of `x` converted from degrees to radians.

Example:

``    deg2rad(180) = pi``

``    rad2deg(x)                                    #=> Float | Complex``

Returns the value of `x` converted from radians to degrees.

Example:

``    rad2deg(pi) = 180``

# INTEGER FUNCTIONS

All operations in this section are done with integers.

## iadd | isub | imul | ipow

``````    iadd(x, y)                                    #=> Int | NaN
isub(x, y)                                    #=> Int | NaN
imul(x, y)                                    #=> Int | NaN
ipow(x, y)                                    #=> Int | NaN``````

Integer addition, subtraction, multiplication and exponentiation.

## idiv | idiv_ceil | idiv_round | idiv_trunc

``````    idiv(x, y)                                    #=> Int | NaN
idiv_ceil(x, y)                               #=> Int | NaN
idiv_trunc(x, y)                              #=> Int | NaN
idiv_round(x, y)                              #=> Int | NaN``````

Integer division: `floor(a/b)`, `ceil(a/b)`, `trunc(a/b)`, `round(a/b)`.

## ipow2

``    ipow2(n)                                      #=> Int``

Raises `2` to the power `n`, by first truncating `n` to an integer. Returns `0` when `n` is negative.

## ipow10

``    ipow10(n)                                     #=> Int``

Raises `10` to the power `n`, by first truncating `n` to an integer. Returns `0` when `n` is negative.

## imod

``    imod(x, y)                                    #=> Int | NaN``

The integer modulus operation. Returns NaN when `y` is zero.

``    addmod(a, b, m)                               #=> Int | NaN``

Modular integer addition: `(a+b) % m`.

``    say addmod(43, 97, 127)     # == (43+97)%127``

## submod

``    submod(a,b,m)                                 #=> Int | NaN``

Modular integer subtraction: `(a-b) % m`.

``    say submod(43, 97, 127)     #=> (43-97)%127``

## mulmod

``    mulmod(a,b,m)                                 #=> Int | NaN``

Modular integer multiplication: `(a*b) % m`.

``    say mulmod(43, 97, 127)     # == (43*97)%127``

## divmod

``````    divmod(a, b)                                  #=> (Int, Int) | (NaN, NaN)
divmod(a, b, m)                               #=> (Int, Int) | (NaN, NaN)``````

When only two arguments are provided, it returns `(idiv(a,b), imod(a,b))`.

When three arguments are given, it does integer modular division: `(a/b) % m`.

``    say divmod(43, 97, 127)     # == (43 * invmod(97, 127))%127``

## invmod

``    invmod(x, y)                                  #=> Int | NaN``

Computes the multiplicative inverse of `x` modulo `y` and returns the result.

When no inverse exists (i.e.: `gcd(x, y) != 1`), the NaN value is returned.

## powmod

``    powmod(x, y, z)                               #=> Int | NaN``

Computes `(x ** y) % z`, where all three values are integers.

Returns NaN when the third argument is 0, or when `y` is negative and `gcd(x, z) != 1`.

``    quadratic_powmod(a, b, w, n, m)               #=> Int | NaN``

Computes `(a + b*sqrt(w))**n % m`, returning `(x,y)` satisfying:

``    x + y*sqrt(w) == (a + b*sqrt(w))**n (mod m)``

## isqrt | icbrt

``````    isqrt(n)                                      #=> Int | NaN
icbrt(n)                                      #=> Int | NaN``````

The integer square root of `n` and the integer cube root of `n`. Returns NaN when a real root does not exist.

## isqrtrem

``    isqrtrem(n)                                   #=> (Int, Int) | (NaN, NaN)``

The integer part of the square root of `n` and the remainder `n - isqrt(n)**2`, which will be zero when `n` is a perfect square.

## iroot

``    iroot(n, m)                                   #=> Int | NaN``

The integer `m-th` root of `n`. Returns NaN when a real does not exist.

## irootrem

``    irootrem(n, m)                                #=> (Int, Int) | (NaN, NaN)``

The integer part of the root of `n` and the remainder `n - iroot(n,m)**m`.

Returns `(NaN,NaN)` when a real root does not exist.

## ilog

``````    ilog(n)                                       #=> Int | NaN
ilog(n, m)                                    #=> Int | NaN``````

The integer part of the logarithm of `n` to base `m` or base e when `m` is not specified.

`n` must be greater than 0 and `m` must be greater than 1. Returns NaN otherwise.

## ilog2 | ilog10

``````    ilog2(n)                                      #=> Int | NaN
ilog10(n)                                     #=> Int | NaN``````

The integer part of the logarithm of `n` to base `2` or base `10`, respectively.

## and | or | xor | not | lsft | rsft

``````    x & y                                         #=> Int
x | y                                         #=> Int
x ^ y                                         #=> Int
~x                                            #=> Int
x << y                                        #=> Int
x >> y                                        #=> Int``````

The bitwise integer operations.

## lcm

``    lcm(@list)                                    #=> Int``

The least common multiple of a list of integers.

## gcd

``    gcd(@list)                                    #=> Int``

The greatest common divisor of a list of integers.

## gcdext

``    gcdext(n, k)                                  #=> (Int, Int, Int)``

The extended greatest common divisor of `n` and `k`, returning `(u, v, d)`, where `d` is the greatest common divisor of `n` and `k`, while `u` and `v` are the coefficients satisfying `u*n + v*k = d`. The value of `d` is always non-negative.

## valuation

``    valuation(n, k)                               #=> Scalar``

Returns the number of times `n` is divisible by `k`.

## remdiv

``    remdiv(n, k)                                  #=> Int``

Removes all occurrences of the divisor `k` from integer `n`.

In general, the following statement holds true:

``    remdiv(n, k) == n / k**(valuation(n, k))``

## kronecker

``    kronecker(n, m)                               #=> Scalar``

Returns the Kronecker symbol (n|m), which is a generalization of the Jacobi symbol for all integers m.

## faulhaber_sum

``    faulhaber_sum(n, k)                           #=> Int | NaN``

Computes the power sum `1^k + 2^k + 3^k +...+ n^k`, using Faulhaber's formula.

The value for `k` must be a non-negative integer. Returns NaN otherwise.

Example:

``    faulhaber_sum(5, 2) = 1^2 + 2^2 + 3^2 + 4^2 + 5^2 = 55``

## geometric_sum

``    geometric_sum(n, r)                           #=> Any``

Computes the geometric sum `1 + r + r^2 + r^3 + ... + r^n`, using the following formula:

``    geometric_sum(n, r) = (r^(n+1) - 1) / (r - 1)``

Example:

``    geometric_sum(5, 8) = 8^0 + 8^1 + 8^2 + 8^3 + 8^4 + 8^5 = 37449``

## dirichlet_sum

``    dirichlet_sum(n, \&f, \&g, \&F, \&G)          #=> Int | NaN``

Given two arithmetic functions `f` and `g`, it computes the following sum in `O(sqrt(n))` steps:

``    Sum_{k=1..n} Sum_{d|k} f(d) * g(k/d)``

The `F` and `G` functions are the partial sums of `f` and `g`, respectively:

``````    F(n) = Sum_{k=1..n} f(k)
G(n) = Sum_{k=1..n} g(k)``````

However, this method is fast only when `F(n)` and `G(n)` can be computed efficiently.

Example:

``````    # Computes:
#   Sum_{k=1..10^9} sigma_2(k) (C.f. A188138)

dirichlet_sum(
10**9,                              # n
sub { 1 },                          # f
sub { \$_**2 },                   # g
sub { \$_ },                      # F(n) = Sum_{k=1..n} f(k)
sub { faulhaber_sum(\$_, 2) },    # G(n) = Sum_{k=1..n} g(k)
)``````

## harmonic | harmfrac

``    harmonic(n)                                   #=> Rat | NaN``

Returns the n-th Harmonic number `H_n`. The harmonic numbers are the sum of reciprocals of the first `n` natural numbers: `1 + 1/2 + 1/3 + ... + 1/n`.

For values greater than 7000, binary splitting (Fredrik Johansson's elegant formulation) is used.

## secant_number

``    secant_number(n)                              #=> Int``

Returns the n-th secant number (A000364), starting with `secant_number(0) = 1`.

## tangent_number

``    tangent_number(n)                             #=> Int``

Returns the n-th tangent number (A000182), starting with `tangent_number(1) = 1`.

## bernoulli_polynomial

``    bernoulli_polynomial(n, x)                    #=> Any``

Returns the n-th Bernoulli polynomial: `B_n(x)`.

## faulhaber_polynomial | faulhaber

``    faulhaber_polynomial(n, x)                        #=> Any``

Returns the n-th Faulhaber polynomial: `F_n(x)`.

## euler_polynomial

``    euler_polynomial(n, x)                        #=> Any``

Returns the n-th Euler polynomial: `E_n(x)`.

## bernoulli | bernfrac

``````    bernoulli(n)                                  #=> Rat | NaN
bernoulli(n, x)                               #=> Any``````

Returns the n-th Bernoulli number `B_n` as an exact fraction, with `bernoulli(1) = 1/2`.

When an additional argument is provided, it returns the n-th Bernoulli polynomial: `B_n(x)`.

## euler

``````    euler(n)                                      #=> Rat | NaN
euler(n, x)                                   #=> Any``````

Returns the n-th Euler number `E_n`, starting with `euler(0) = 1`.

When an additional argument is provided, it returns the n-th Euler polynomial: `E_n(x)`.

## lucas

``    lucas(n)                                      #=> Int | NaN``

The n-th Lucas number. Returns NaN when `n` is negative.

## lucasU

``    lucasU(P, Q, n)                               #=> Int | NaN``

The Lucas `U_n(P, Q)` function.

Example:

``````    lucasU(1, -1, \$n)       # the Fibonacci numbers
lucasU(2, -1, \$n)       # the Pell numbers
lucasU(1, -2, \$n)       # the Jacobsthal numbers``````

## lucasV

``    lucasV(P, Q, n)                               #=> Int | NaN``

The Lucas `V_n(P, Q)` function.

Example:

``````    lucasV(1, -1, \$n)       # the Lucas numbers
lucasV(2, -1, \$n)       # the Pell-Lucas numbers
lucasV(1, -2, \$n)       # the Jacobsthal-Lucas numbers``````

## lucasmod

``    lucasmod(n, m)                                #=> Int | NaN``

Efficiently compute the n-th Lucas number modulo m.

## lucasUmod

``    lucasUmod(P, Q, n, m)                         #=> Int | NaN``

Efficiently compute the Lucas `U_n(P, Q)` function modulo m.

## lucasVmod

``    lucasVmod(P, Q, n, m)                         #=> Int | NaN``

Efficiently compute the Lucas `V_n(P, Q)` function modulo m.

## fibonacci

``````    fibonacci(n)                                  #=> Int | NaN
fibonacci(n, k)                               #=> Int | NaN``````

The n-th Fibonacci number. Returns NaN when `n` is negative.

When `k` is specified, it returns the k-th order Fibonacci number.

Example:

``````    say fibonacci(100, 3);        # 100th Tribonacci number
say fibonacci(100, 4);        # 100th Tetranacci number
say fibonacci(100, 5);        # 100th Pentanacci number``````

## fibmod

``    fibmod(n, m)                                  #=> Int | NaN``

Efficiently compute the n-th Fibonacci number modulo m.

## chebyshevT

``    chebyshevT(n, x)                              #=> Any``

Compute the Chebyshev polynomials of the first kind: `T_n(x)`, where `n` must be a native integer.

Defined as:

``````    T(0, x) = 1
T(1, x) = x
T(n, x) = 2*x*T(n-1, x) - T(n-2, x)``````

## chebyshevU

``    chebyshevU(n, x)                              #=> Any``

Compute the Chebyshev polynomials of the second kind: `U_n(x)`, where `n` must be a native integer.

Defined as:

``````    U(0, x) = 1
U(1, x) = 2*x
U(n, x) = 2*x*U(n-1, x) - U(n-2, x)``````

## chebyshevTmod

``    chebyshevTmod(n, x, m)                        #=> Int | NaN``

Compute the modular Chebyshev polynomials of the first kind: `T_n(x) mod m`, where `n` must be an integer.

## chebyshevUmod

``    chebyshevUmod(n, x, m)                        #=> Int | NaN``

Compute the modular Chebyshev polynomials of the second kind: `U_n(x) mod m`, where `n` must be an integer.

## laguerreL

``    laguerreL(n, x)                               #=> Any``

Compute the Laguerre polynomials: `L_n(x)`, where `n` must be a non-negative native integer.

## legendreP

``    legendreP(n, x)                               #=> Any``

Compute the Legendre polynomials: `P_n(x)`, where `n` must be a non-negative native integer.

## hermiteH

``    hermiteH(n, x)                                #=> Any``

Compute the physicists' Hermite polynomials: `H_n(x)`, where `n` must be a non-negative native integer.

## hermiteHe

``    hermiteHe(n, x)                               #=> Any``

Compute the probabilists' Hermite polynomials: `He_n(x)`, where `n` must be a non-negative native integer.

## factorial

``    factorial(n)                                  #=> Int | NaN``

Factorial of `n` (denoted as `n!`). Returns NaN when `n` is negative. (`1*2*3*...*n`)

## dfactorial

``    dfactorial(n)                                 #=> Int | NaN``

Double-factorial of `n` (denoted as `n!!`). Returns NaN when `n` is negative. (requires GMP>=5.1.0)

Example:

``````    dfactorial(7)     # 1*3*5*7 = 105
dfactorial(8)     # 2*4*6*8 = 384``````

## mfactorial

``    mfactorial(n, m)                              #=> Int | NaN``

Generalized m-factorial of `n`. Returns NaN when `n` or `m` is negative. (requires GMP>=5.1.0)

## subfactorial

``````    subfactorial(n)                               #=> Int | NaN
subfactorial(n, k)                            #=> Int | NaN``````

The number of permutations of `{1, ..., n}` that have exactly `k` fixed points, given a positive integer `n` and an optional integer `k` (if `k` is omitted, then `k=0`).

## superfactorial

``    superfactorial(n)                             #=> Int | NaN``

Product of first `n` factorials: `Prod_{k=1..n} k!`.

## hyperfactorial

``    hyperfactorial(n)                             #=> Int | NaN``

Hyperfactorial of `n`, defined as: `Prod_{k=1..n} k^k`.

## bell

``    bell(n)                                       #=> Int | NaN``

Returns the n-th Bell number.

## catalan

``````    catalan(n)                                    #=> Int | NaN
catalan(n, k)                                 #=> Int | NaN``````

Returns the n-th Catalan number.

If two arguments are provided, it returns the `C(n,k)` entry in Catalan's triangle.

## binomial

``    binomial(n, k)                                #=> Int | NaN``

Computes the binomial coefficient `n` over `k`, also called the "choose" function. The result is equivalent to:

``````                        n!
binomial(n, k) = -------
k!(n-k)!``````

## multinomial

``    multinomial(a, b, c, ...)                     #=> Int | NaN``

Computes the multinomial coefficient, given a list of native integers.

Example:

``    multinomial(1, 4, 4, 2) = 34650``

## rising_factorial

``    rising_factorial(n, k)                        #=> Int | Rat | NaN``

Rising factorial, `n * (n + 1) * ... * (n + k - 1)`, defined as:

``    binomial(n + k - 1, k) * k!``

For negative values of `k`, rising factorial is defined as:

``    rising_factorial(n, -k) = 1/rising_factorial(n - k, k)``

When the denominator is zero, NaN is returned.

## falling_factorial

``    falling_factorial(n, k)                       #=> Int | Rat | NaN``

Falling factorial, `n * (n - 1) * ... * (n - k + 1)`, defined as:

``    binomial(n, k) * k!``

For negative values of `k`, falling factorial is defined as:

``    falling_factorial(n, -k) = 1/falling_factorial(n + k, k)``

When the denominator is zero, NaN is returned.

## primorial

``    primorial(n)                                  #=> Int | NaN``

Returns the product of all the primes less than or equal to `n`. (requires GMP>=5.1.0)

## next_prime

``    next_prime(n)                                 #=> Int | NaN``

Returns the next prime after `n`.

## is_prime

``    is_prime(n, r=23)                             #=> Scalar``

Returns 2 if `n` is definitely prime, 1 if `n` is probably prime (without being certain), or 0 if `n` is definitely composite.

This method does some trial divisions, then `r` Miller-Rabin probabilistic primality tests.

A higher `r` value reduces the chances of a composite being identified as "probably prime". Reasonable values of `r` are between 20 and 50.

Starting with GMP 6.2.0, a Baillie-PSW probable prime test is performed, which has no known counter-examples. By specifying a value of r > 24, if `n` passes the B-PSW test, `r-24` additional Miller-Rabin tests are performed.

## is_coprime

``    is_coprime(n, k)                              #=> Bool``

Returns true when `n` and `k` are relatively prime to each other. That is, when `gcd(n, k) == 1`.

## make_coprime

``    make_coprime(n, k)                            #=> Int | NaN``

Returns the largest divisor of `n` that is coprime to `k`.

## is_rough

``    is_rough(n, k)                                #=> Bool``

Returns true when all the prime factors of `n` are greater than or equal to `k`, where `n` and `k` are positive integers.

Equivalently, it returns true if the smallest prime factor of `n` is greater than or equal to `k`.

Example:

``````    is_rough(55, 7)    # false  : 55 = 5 * 11, where 5 < 7
is_rough(35, 5)    # true   : 35 = 5 * 7``````

## is_smooth

``    is_smooth(n, k)                               #=> Bool``

Returns true when all the prime factors of `n` are less than or equal to `k`, where `n` and `k` are positive integers.

Equivalently, it returns true if the largest prime factor of `n` is less than or equal to `k`.

Example:

``````    is_smooth(36, 3)    # true  : 36 = 2^2 * 3^2
is_smooth(39, 6)    # false : 39 = 3 * 13, where 13 > 6``````

## is_smooth_over_prod

``    is_smooth_over_prod(n, k)                     #=> Bool``

Returns true if `n` can be expressed as a product of primes dividing `k`.

Equivalently, it returns true if `gcd(rad(n), rad(k)) == rad(n)`.

Example:

``````    is_smooth_over_prod(42, 2*3*7*11)   # true because 42 = 2*3*7
is_smooth_over_prod(75, 3*5)        # true because 75 = 3*5*5
is_smooth_over_prod(\$n, 3*5*7*11)   # true for odd 11-smooth numbers \$n``````

## smooth_part

``    smooth_part(n, k)                             #=> Int | NaN``

Returns the largest divisor of `n` that is `k`-smooth.

Example:

``````    smooth_part(3*3*5*7,  5)    # 45 (= 3*3*5)
smooth_part(5*7*7*11, 6)    # 5``````

## rough_part

``    rough_part(n, k)                              #=> Int | NaN``

Returns the largest divisor of `n` that is `k`-rough.

Example:

``````    rough_part(3*3*5*7,  5)    # 35  (= 5*7)
rough_part(5*7*7*11, 6)    # 539 (= 7*7*11)``````

## is_square

``    is_square(n)                                  #=> Bool``

Returns true when `n` is a perfect square. When `n` is not an integer, a false value is returned.

## is_power

``````    is_power(n)                                   #=> Bool
is_power(n, k)                                #=> Bool``````

Returns true when `n` is a perfect power of a given integer `k`.

When `n` is not an integer, it always returns false. On the other hand, when `k` is not an integer, it will implicitly be truncated to an integer. If `k` is not positive after truncation, `0` is returned.

A true value is returned iff there exists some integer `a` satisfying the equation: `a**k = n`.

When `k` is not specified, it returns true if `n` can be expressed as `a**b` for some integers `a` and `b`, with `b` greater than 1.

Example:

``````    is_power(100, 2)       # true: 100 is a square (10**2)
is_power(125, 3)       # true: 125 is a cube   ( 5**3)
is_power(279841)       # true: 279841 is 23**4``````

## is_power_of

``    is_power_of(n, b)                             #=> Bool``

Return true if `n` is a power of `b`, such that `n = b**k` for some k >= 0.

Example:

``````    64->is_power_of(2)     # true: 64 is a power of 2 (64 = 2**6)
27->is_power_of(3)     # true: 27 is a power of 3 (27 = 3**3)``````

## polygonal

``    polygonal(n, k)                               #=> Int``

Returns the nth k-gonal number. When `n` is negative, it returns the second k-gonal number.

Example:

``````    say join(' ', map { polygonal( \$_, 3) } 1..10);  # triangular numbers
say join(' ', map { polygonal( \$_, 5) } 1..10);  # pentagonal numbers
say join(' ', map { polygonal(-\$_, 5) } 1..10);  # second pentagonal numbers``````

## ipolygonal_root

``    ipolygonal_root(n, k)                         #=> Int | NaN``

Integer k-gonal root of `n`. Returns NaN when a real root does not exist.

Example:

``````    say ipolygonal_root(\$n, 5);                  # integer pentagonal root
say ipolygonal_root(polygonal(10, 5), 5);    # prints: "10"``````

## ipolygonal_root2

``    ipolygonal_root2(n, k)                        #=> Int | NaN``

Second integer k-gonal root of `n`. Returns NaN when a real root does not exist.

Example:

``````    say ipolygonal_root2(\$n, 5);                   # second integer pentagonal root
say ipolygonal_root2(polygonal(-10, 5), 5);    # prints: "-10"``````

## is_polygonal

``    is_polygonal(n, k)                            #=> Bool``

Returns true when `n` is a k-gonal number.

The values of `n` and `k` can be any arbitrary large integers.

Example:

``````    say is_polygonal(145, 5);      #=> 1 ("145" is a pentagonal number)
say is_polygonal(155, 5);      #=> 0``````

## is_polygonal2

``    is_polygonal2(n, k)                           #=> Bool``

Returns true when `n` is a second k-gonal number.

The values of `n` and `k` can be any arbitrary large integers.

Example:

``````    say is_polygonal2(145, 5);      #=> 0
say is_polygonal2(155, 5);      #=> 1 ("155" is a second-pentagonal number)``````

# MISCELLANEOUS

This section includes various useful methods.

## min | max

``````    min(@list)                                    #=> Any
max(@list)                                    #=> Any``````

Smallest and greatest value, respectively, from a given list of numbers.

Returns `undef` if the list contains `NaN` or if the list is empty.

## sum | prod

``````    sum(@list)                                    #=> Any
prod(@list)                                   #=> Any``````

Sum and product of a given list of numbers.

## bsearch

``````    bsearch(n, \&f)                               #=> Int | undef
bsearch(a, b, \&f)                            #=> Int | undef``````

Binary search from to `0` to `n`, or from `a` to `b`, which can be any arbitrary large integers.

The last argument is a subroutine reference which does the comparisons.

This function finds a value `k` such that f(k) = 0. Returns `undef` otherwise.

``````    bsearch(20,      sub { \$_*\$_  <=> 49   });   #=> 7   (7*7  = 49)
bsearch(3, 1000, sub { \$_**\$_ <=> 3125 });   #=> 5   (5**5 = 3125)``````

## bsearch_le

``````    bsearch_le(n, \&f)                            #=> Int | undef
bsearch_le(a, b, \&f)                         #=> Int | undef``````

Binary search from to `0` to `n`, or from `a` to `b`, which can be any arbitrary large integers.

The last argument is a subroutine reference which does the comparisons.

This function finds a value `k` such that f(k) <= 0 and f(k+1) > 0. Returns `undef` otherwise.

``````    bsearch_le(10**6,         sub { exp(\$_) <=> 1e+9 });  #=>  20   (exp( 20) <= 1e+9)
bsearch_le(-10**6, 10**6, sub { exp(\$_) <=> 1e-9 });  #=> -21   (exp(-21) <= 1e-9)``````

## bsearch_ge

``````    bsearch_ge(n, \&f)                            #=> Int | undef
bsearch_ge(a, b, \&f)                         #=> Int | undef``````

Binary search from to `0` to `n`, or from `a` to `b`, which can be any arbitrary large integers.

The last argument is a subroutine reference which does the comparisons.

This function finds a value `k` such that f(k-1) < 0 and f(k) >= 0. Returns `undef` otherwise.

``````    bsearch_ge(10**6,         sub { exp(\$_) <=> 1e+9 });  #=>  21   (exp( 21) >= 1e+9)
bsearch_ge(-10**6, 10**6, sub { exp(\$_) <=> 1e-9 });  #=> -20   (exp(-20) >= 1e-9)``````

## floor

``    floor(x)                                      #=> Any``

Returns `x` if `x` is an integer, otherwise it rounds `x` towards -Infinity.

Example:

``````    floor( 2.5) =  2
floor(-2.5) = -3``````

## ceil

``    ceil(x)                                       #=> Any``

Returns `x` if `x` is an integer, otherwise it rounds `x` towards +Infinity.

Example:

``````    ceil( 2.5) =  3
ceil(-2.5) = -2``````

## round

``````    round(x)                                      #=> Any
round(x, p)                                   #=> Any``````

Rounds `x` to the nth place. A negative argument rounds that many digits after the decimal point, while a positive argument rounds that many digits before the decimal point.

Example:

``````    round('1234.567')         = 1235
round('1234.567', 2)      = 1200
round('3.123+4.567i', -2) = 3.12+4.57*i``````

## rand

``````    rand(x)                                       #=> Float
rand(x, y)                                    #=> Float``````

Returns a pseudorandom floating-point value. When an additional argument is provided, it returns a number between `x` (inclusive) and `y` (exclusive). Otherwise, returns a number between `0` (inclusive) and `x` (exclusive).

If `x` is greater than `y`, the returned value will be in the range `[y, x)`.

The PRNG behind this function is called the "Mersenne Twister". Although it generates pseudorandom numbers of very good quality, it is NOT cryptographically secure. You should not rely on it in security-sensitive situations.

Example:

``````    rand(10)        # a pseudorandom floating-point in the interval [0, 10)
rand(10, 20)    # a pseudorandom floating-point in the interval [10, 20)``````

## irand

``````    irand(x)                                      #=> Int
irand(x, y)                                   #=> Int``````

Returns a pseudorandom integer. Unlike the `rand()` function, `irand()` is inclusive in both sides.

When an additional argument is provided, it returns an integer between `x` (inclusive) and `y` (inclusive), otherwise returns an integer between `0` (inclusive) and `x` (inclusive).

If `x` is greater than `y`, the returned integer will be in the range `[y, x]`.

The PRNG behind this function is called the "Mersenne Twister". Although it generates high-quality pseudorandom integers, it is NOT cryptographically secure. You should not rely on it in security-sensitive situations.

Example:

``````    irand(10)        # a pseudorandom integer in the interval [0, 10]
irand(10, 20)    # a pseudorandom integer in the interval [10, 20]``````

## seed | iseed

``````    seed(n)                                       #=> Int
iseed(n)                                      #=> Int``````

Reseeds the `rand()` and the `irand()` function, respectively, with the value of `n`, which can be any arbitrary large integer.

Returns back the integer part of `n`. If `n` cannot be truncated to an integer, the method dies with an appropriate error message.

## sgn

``    sgn(x)                                        #=> Scalar | Complex``

Returns `-1` when `x` is negative, `1` when `x` is positive, and `0` when `x` is zero.

When `x` is a complex number, it computes the sign using the identity:

``    sgn(x) = x / abs(x)``

## length

``````    \$n->length                                    #=> Scalar
\$n->length(\$base)                             #=> Scalar``````

Returns the number of digits of the integer part of `n` in a given base (default 10).

Example:

``````    5040->length        # size in base 10
5040->length(2)     # size in base 2``````

Returns `undef` when `n` cannot be truncated to an integer.

## inc

``````    ++\$x                                          #=> Any
\$x++                                          #=> Any``````

Returns `x + 1`.

## dec

``````    --\$x                                          #=> Any
\$x--                                          #=> Any``````

Returns `x - 1`.

## copy

``    \$x->copy                                      #=> Any``

Returns a deep-copy of the self-object.

## popcount

``    popcount(n)                                   #=> Scalar``

Returns the population count of the positive integer part of `x`, which is the number of 1's in its binary representation.

Returns `undef` when `n` cannot be truncated to an integer.

This value is also known as the Hamming weight value.

Example:

``    popcount(0b1011) = 3``

## hamdist

``    hamdist(n, k)                                 #=> Scalar``

Returns the Hamming distance (number of bit-positions where the bits differ) between integers `n` and `k`.

Returns `undef` when `n` or `k` cannot be truncated to an integer.

## getbit

``    getbit(n, k)                                  #=> Bool``

Returns 1 if bit `k` of `n` is set, and 0 if it is not set.

Returns `undef` when `n` cannot be truncated to an integer or when `k` is negative.

Example:

``````    getbit(0b1001, 0) = 1
getbit(0b1000, 0) = 0``````

## setbit

``    setbit(n, k)                                  #=> Int``

Returns a copy of `n` with bit `k` set to 1.

Example:

``````    setbit(0b1000, 0) = 0b1001
setbit(0b1000, 2) = 0b1100``````

## flipbit

``    flipbit(n, k)                                 #=> Int``

Returns a copy of `n` with bit `k` inverted.

Example:

``````    flipbit(0b1000, 0) = 0b1001
flipbit(0b1001, 0) = 0b1000``````

## clearbit

``    clearbit(n, k)                                #=> Int``

Returns a copy of `n` with bit `k` set to 0.

Example:

``````    clearbit(0b1001, 0) = 0b1000
clearbit(0b1100, 2) = 0b1000``````

## bit_scan0 | bit_scan1

``````    bit_scan0(n, k)                               #=> Scalar
bit_scan1(n, k)                               #=> Scalar``````

Scan `n`, starting from bit index `k`, towards more significant bits, until 0 or 1 bit (respectively) is found.

When `k` is omitted, `k=0` is assumed.

Returns `undef` if `n` cannot be truncated to an integer or if `k` is negative.

# * Introspection

## is_int

``    is_int(x)                                     #=> Bool``

Returns true when `x` is an integer.

## is_rat

``    is_rat(x)                                     #=> Bool``

Returns true when `x` is a rational number.

## is_real

``    is_real(x)                                    #=> Bool``

Returns true when `x` is a real number (i.e.: when the imaginary part is zero and it holds a real value in the real part).

Example:

``````    is_real(complex('4'))           # true
is_real(complex('4i'))          # false (is imaginary)
is_real(complex('3+4i'))        # false (is complex)``````

## is_imag

Returns true when `x` is an imaginary number (i.e.: when the real part is zero and it has a non-zero imaginary part).

Example:

``````    is_imag(complex('4'))           # false (is real)
is_imag(complex('4i'))          # true
is_imag(complex('3+4i'))        # false (is complex)``````

## is_complex

``    is_complex(x)                                 #=> Bool``

Returns true when `x` is a complex number (i.e.: when the real part and the imaginary part are non-zero).

Example:

``````    is_complex(complex('4'))        # false (is real)
is_complex(complex('4i'))       # false (is imaginary)
is_complex(complex('3+4i'))     # true``````

## is_even

``    is_even(n)                                    #=> Bool``

Returns true when `n` is a real integer divisible by 2.

## is_odd

``    is_odd(n)                                     #=> Bool``

Returns true when `n` is a real integer not divisible by 2.

## is_div

``    is_div(n, k)                                  #=> Bool``

Returns true when `n` is exactly divisible by `k` (i.e.: when the remainder `n % k` is zero).

Also defined for rationals, floats and complex numbers.

## is_congruent

``    is_congruent(n, k, m)                         #=> Bool``

Returns true when `n` is congruent to `k` modulo `m` (i.e.: when the remainder `n % m` equals `k % m`).

Also defined for rationals, floats and complex numbers.

## is_pos

``    is_pos(x)                                     #=> Bool``

Returns true when `x` is positive.

## is_neg

``    is_neg(x)                                     #=> Bool``

Returns true when `x` is negative.

## is_zero

``    is_zero(n)                                    #=> Bool``

Returns true when `n` equals 0.

## is_one

``    is_one(n)                                     #=> Bool``

Returns true when `n` equals 1.

## is_mone

``    is_mone(n)                                    #=> Bool``

Returns true when `n` equals -1.

## is_inf

``    is_inf(x)                                     #=> Bool``

Returns true when `x` holds the positive Infinity special value.

## is_ninf

``    is_ninf(x)                                    #=> Bool``

Returns true when `x` holds the negative Infinity special value.

## is_nan

``    is_nan(x)                                     #=> Bool``

Returns true when `x` holds the Not-a-Number special value.

# * Conversions

## int

``    int(x)                                        #=> Int | NaN``

Returns the integer part of `x`. Returns NaN when `x` cannot be truncated to an integer.

## rat

``````    rat(x)                                        #=> Rat | NaN
rat(str)                                      #=> Rat | NaN``````

Converts `x` to a rational number. Returns NaN when this conversion is not possible.

When the given argument is a decimal expansion string, it will be specially parsed as an exact fraction.

If `x` is a floating-point real number, consider using `rat_approx()` instead.

Example:

``````    rat('0.5')       = 1/2
rat('1234/5678') = 617/2839``````

## rat_approx

``    rat_approx(n)                                 #=> Rat | NaN``

Given a real number `n`, it returns a very good (sometimes exact) rational approximation to `n`, computed with continued fractions.

Example:

``````    rat_approx(3.14)     = 22/7
rat_approx(zeta(-5)) = -1/252``````

Returns NaN when `n` is not a real number.

## ratmod

``    ratmod(r, m)                                  #=> Int | NaN``

Given a rational number `r` and an integer `m`, it returns `r % m` computed as an integer.

Example:

``    ratmod('43/97', 127) = 79``

Equivalent with:

``    (numerator(\$r) * invmod(denominator(\$r), \$m)) % \$m``

## float

``````    float(x)                                      #=> Float | Complex
float(str)                                    #=> Float | Complex``````

Converts `x` to a real or a complex floating-point number (in this order).

Example:

``````    float(3.1415926) = 3.1415926   (as Float)
float('777/222') = 3.5         (as Float)
float('123+45i') = 123 + 45*i  (as Complex)``````

## complex

``````    complex(x)                                    #=> Complex
complex(str)                                  #=> Complex
complex(x, y)                                 #=> Complex``````

Converts `x` to a complex number. When a second argument is given, it sets `x` as the real part and `y` as the imaginary part.

If `x` or `y` are complex numbers, the function returns the result of `x + y*i`.

Example:

``````    complex("3+4i")        = 3+4*i
complex(3, 4)          = 3+4*i
complex("5+2i", "-4i") = 9+2*i``````

## stringify

``    "\$x"                                          #=> Scalar``

Returns a string representing the value of `x`, in base 10.

## boolify

``    !!\$x                                          #=> Bool``

Returns a false value when the number is zero or when the value of the number is `NaN`. True otherwise.

## numify

``    \$x->numify                                    #=> Scalar``

Returns a Perl numerical scalar containing the value of `x`, truncated if necessary.

If `x` is an integer that fits inside a native signed or unsigned integer, the returned result will be exact, otherwise the result is returned as a double, with possible truncation.

If `x` is a complex number, only the real part is considered.

## base

``    base(n, b)                                    #=> Scalar``

Returns a string-representation of `n` in a given base `b` (between 2 and 62), where `n` can be any type of number, including a floating-point or a complex number.

Example:

``````    base(42, 2)         = "101010"
base(17.5, 36)      = "h.i"
base("99/43", 16)   = "63/2b"
base("17.5+5i", 36) = "(h.i 5)"``````

The output of this function can be passed to new(), along with the base-number, which converts it back to the original number:

``````    say Math::AnyNum->new("101010", 2);    #=> 42
say Math::AnyNum->new("h.i", 36);      #=> 17.5``````

## as_bin

``    as_bin(n)                                     #=> Scalar``

Returns a string representing the integer part of `n` in binary (base 2).

Example:

``    as_bin(42) = "101010"``

Returns `undef` when `n` cannot be converted to an integer.

## as_oct

``    as_oct(n)                                     #=> Scalar``

Returns a string representing the integer part of `n` in octal (base 8).

Example:

``    as_oct(42) = "52"``

Returns `undef` when `n` cannot be converted to an integer.

## as_hex

``    as_hex(n)                                     #=> Scalar``

Returns a string representing the integer part of `n` in hexadecimal (base 16).

Example:

``    as_hex(42) = "2a"``

Returns `undef` when `n` cannot be converted to an integer.

## as_int

``````    as_int(n)                                     #=> Scalar
as_int(n, b)                                  #=> Scalar``````

Returns the integer part of `n` as a string, in a given base, where the base must be between 2 and 62.

When the base is omitted, it defaults to base 10.

Example:

``````    as_int(255)     = "255"
as_int(255, 16) = "ff"``````

Returns `undef` when `n` cannot be converted to an integer.

## as_rat

``````    as_rat(n)                                     #=> Scalar
as_rat(n, b)                                  #=> Scalar``````

Returns `n` as a rational string-representation in a given base, where the base must be between 2 and 62.

When the base is omitted, it defaults to base 10.

Example:

``````    as_rat(42)      = "42"
as_rat("2/4")   = "1/2"
as_rat(255, 16) = "ff"``````

Returns `undef` when `n` cannot be converted to a rational number.

## as_frac

``````    as_frac(n)                                    #=> Scalar | undef
as_frac(n, b)                                 #=> Scalar | undef``````

Returns `n` as a fraction in a given base, where the base must be between 2 and 62.

When the base is omitted, it defaults to base 10.

Example:

``````    as_frac(42)      = "42/1"
as_frac("2/4")   = "1/2"
as_frac(255, 16) = "ff/1"``````

Returns `undef` when `n` cannot be converted to a rational number.

## as_dec

``````    as_dec(n)                                     #=> Scalar
as_dec(n, digits)                             #=> Scalar``````

Returns `n` as a decimal expansion string, with an optional number of digits.

When the second argument is undefined, it uses the default precision.

The value of `n` can also be a complex number.

Example:

``````    as_dec(1/2)        = "0.5"
as_dec(sqrt(2), 3) = "1.41"``````

# * Dissections

## numerator

``    numerator(x)                                  #=> Int | NaN``

Returns the numerator of `x` as a signed `Math::AnyNum` object. When `x` is not a rational number, it tries to convert it to a rational. Returns NaN when this conversion is not possible.

Example:

``````    numerator("-42")  = -42
numerator("-3/4") = -3``````

## denominator

``    denominator(x)                                #=> Int | NaN``

Returns the denominator of `x` as an unsigned `Math::AnyNum` object. When `x` is not a rational number, it tries to convert it to a rational. Returns NaN when this conversion is not possible.

Example:

``````    denominator("-42")  = 1
denominator("-3/4") = 4``````

## nude

``    nude(x)                                       #=> (Int | NaN, Int | NaN)``

Returns the numerator and the denominator of `x`.

Example:

``````    nude("42")   = (42, 1)
nude("-3/4") = (-3, 4)``````

## real

``    real(x)                                       #=> Any``

Returns the real part of `x`.

Example:

``````    real("42")   = 42
real("42i")  = 0
real("3-4i") = 3``````

## imag

``    imag(x)                                       #=> Any``

Returns the imaginary part of `x`, if any. Otherwise, returns zero.

Example:

``````    imag("42")   =  0
imag("42i")  = 42
imag("3-4i") = -4``````

## reals

``    reals(x)                                      #=> (Any, Any)``

Returns the real and the imaginary part of `x` as real numbers.

Example:

``````    reals("42")   = (42, 0)
reals("42i")  = (0, 42)
reals("3-4i") = (3, -4)``````

## digits

``````    digits(n)                                     #=> (Scalar, Scalar, ...)
digits(n, b)                                  #=> (Scalar | Int, Scalar | Int, ...)``````

Returns a list with the digits of `n` in a given base. When no base is specified, it defaults to base 10.

Only the absolute integer part of `n` is considered.

The value of `b` must be greater than `1`. Returns an empty list otherwise.

Example:

``````    digits(12345)      = (5, 4, 3, 2, 1)
digits(12345, 100) = (45, 23, 1)``````

## digits2num

``    digits2num([...], b=10)                       #=> Int | NaN``

Takes an array-ref of digits (in reverse order) and an optional base (default 10), converting the digits to an integer in the given base.

The value of `b` must be greater than `1`. Returns NaN otherwise.

Example:

``````    digits2num([5, 4, 3, 2, 1])  = 12345
digits2num([45, 23, 1], 100) = 12345``````

## sumdigits

``````    sumdigits(n)                                  #=> Int | NaN
sumdigits(n, b)                               #=> Int | NaN``````

Sum the digits of `n` in a given base. When no base is specified, it defaults to base 10.

Only the absolute integer part of `n` is considered.

The value of `b` must be greater than `1`. Returns NaN otherwise.

Example:

``````    sumdigits(12345)      = 15
sumdigits(12345, 100) = 69``````

# * Comparisons

## eq

``    x == y                                        #=> Bool``

Equality check: returns a true value when `x` and `y` are equal.

## ne

``    x != y                                        #=> Bool``

Inequality check: returns a true value when `x` and `y` are not equal.

## gt

``    x > y                                         #=> Bool``

Returns true when `x` is greater than `y`.

## ge

``    x >= y                                        #=> Bool``

Returns true when `x` is equal or greater than `y`.

## lt

``    x < y                                         #=> Bool``

Returns true when `x` is less than `y`.

## le

``    x <= y                                        #=> Bool``

Returns true when `x` is equal or less than `y`.

## cmp

``    x <=> y                                       #=> Scalar``

Compares `x` to `y` and returns a negative value when `x` is less than `y`, 0 when `x` and `y` are equal, and a positive value when `x` is greater than `y`.

Complex numbers are compared as:

``````    (real(x) <=> real(y)) ||
(imag(x) <=> imag(y))``````

Comparing anything to NaN (including NaN itself), returns `undef`.

## acmp

``    acmp(x, y)                                    #=> Scalar``

Absolute comparison of `x` and `y`.

Defined as:

``    acmp(x, y) = abs(x) <=> abs(y)``

## approx_cmp

``````    approx_cmp(x, y)                              #=> Scalar
approx_cmp(x, y, k)                           #=> Scalar``````

Approximate comparison, by rounding the values of `x` and `y` at a given number of decimal places.

A negative value for `k` rounds that many digits after the decimal point, while a positive value rounds before the decimal point.

When no value is given for `k`, it uses the default precision - 1.

# PERFORMANCE

The performance varies greatly, but, in most cases, Math::AnyNum is between 2x up to 10x faster than Math::BigFloat with the GMP backend, and about 100x faster than Math::BigFloat without the GMP backend (to be modest).

Math::AnyNum is fast because of the following facts:

• minimal overhead in object creations and conversions.

• minimal Perl code is executed per operation.

• the GMP, MPFR and MPC libraries are extremely efficient.

To achieve the best performance, try to:

• use the i* functions/methods wherever applicable.

• use floating-point numbers when accuracy is not important.

• pass Perl integers as arguments to methods, if you can.

# MOTIVATION

This module came into existence as a response to Dana Jacobsen's request for a transparent interface to Math::GMPz and Math::MPFR, which he talked about at the YAPC NA, in 2015.

See his great presentation at: https://www.youtube.com/watch?v=Dhl4_Chvm_g.

The main aim of this module is to provide a fast and correct alternative to Math::BigInt, Math::BigFloat and Math::BigRat, as well as to bigint, bignum and bigrat pragmas.

The original project was called `Math::BigNum`, but because of some design flaws, that project was abandoned and much of its code ended up in this module.

• Fast math libraries

Math::GMP - High speed arbitrary size integer math.

Math::GMPz - perl interface to the GMP library's integer (mpz) functions.

Math::GMPq - perl interface to the GMP library's rational (mpq) functions.

Math::MPFR - perl interface to the MPFR (floating point) library.

Math::MPC - perl interface to the MPC (multi precision complex) library.

• Portable math libraries

Math::BigInt - Arbitrary size integer/float math package.

Math::BigFloat - Arbitrary size floating point math package.

Math::BigRat - Arbitrary big rational numbers.

• Math utilities

Math::Prime::Util - Utilities related to prime numbers, including fast sieves and factoring.

Math::GComplex - Generic library for complex number operations, with support for Gaussian integers.

# REPOSITORY

https://github.com/trizen/Math-AnyNum

# AUTHOR

Daniel Șuteu, `<trizen at cpan.org>`