The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Sidef::Types::Number::Number

DESCRIPTION

The Number class implements support for numerical operations, supporting integers, rationals, floating-points and complex numbers at arbitrary precision.

This class also implements many useful mathematical methods, from basic arithmetical operations, to advanced number-theoretic functions, including primality testing and prime factorization methods.

SYNOPSIS

    var a = Num(string)
    var b = Number(string, base)

INHERITS

Inherits methods from:

       * Sidef::Object::Object

METHODS

!

    n!

Factorial of n. (1*2*3*...*n)

Aliases: fac, factorial

!!

    n!!

Double-factorial of n.

Aliases: dfac, dfactorial, double_factorial

%

    n % k

Remainder of n/k.

Aliases: mod

%%

    n %% k

Returns true if n is divisible by k. False otherwise.

Aliases: is_div

&

    a & b

Bitwise AND operation.

Aliases: and

*

    a * b

Multiplication of a and b.

Aliases: mul

**

    a**b

Exponentiation: a to power b.

Aliases: pow

+

    a + b

Addition of a and b.

Aliases: add

++

    n++
    ++n
    n.inc

Increment n by 1 and return the result.

Aliases: inc

-

    a - b

Subtraction of a and b.

Aliases: sub

--

    n--
    --n
    n.dec

Decrement n by 1 and return the result.

Aliases: dec

..

    a .. b

Create an inclusive-inclusive RangeNum object, from a to b.

Equivalent with:

    RangeNum(a, b)

Aliases: to, upto

..^

    a ..^ b

Create an inclusive-exclusive RangeNum object, from a to b-1.

Equivalent with:

    RangeNum(a, b-1)

Aliases: xto, xupto

/

    a / b

Division of a by b.

Aliases: ÷, div

//

    a // b

Integer floor-division of a and b.

When a and b are integers, this is equivalent with:

    floor(a/b)

Aliases: idiv

:

    a : b

Create a new complex number.

Equivalent with:

    Complex(a, b)

Aliases: pair

<

    a < b

Returns true if a is less than b.

Aliases: lt

<<

    a << b

Left shift a by b bits, which is equivalent with (assuming a and b are integers):

    floor(a * 2**b)

Aliases: lsft, shift_left

<=>

    a <=> b

Comparison of a with b. Returns -1 if a is less than b, 0 if a and b are equal and +1 if a is greater than b.

Aliases: cmp

approx_cmp

    a <~> b
    approx_cmp(a, b)
    approx_cmp(a, b, k)

Approximate comparison of a and b.

Equivalent with:

    a.round(k) <=> b.round(k)

When k is omitted, it uses the default floating-point precision to deduce k.

==

    a == b

Equality check. Returns true if a and b are equal.

Aliases: eq

>

    a > b

Returns true if a is greater than b. False otherwise.

Aliases: gt

>>

    a >> b

Right shift a by b bits, which is equivalent with (assuming a and b are integers):

    floor(a / 2**b)

Aliases: rsft, shift_right

^

    a ^ b

Bitwise XOR operation.

Aliases: xor

^..

    a ^.. b

Creates a reversed exclusive-inclusive RangeNum object, from a-1 down to b.

Equivalent with:

    RangeNum(a-1, b, -1)

Aliases: xdownto

C

    Num.C
    Num.catalan_G

Returns the Catalan constant: 0.915965594177...

Aliases: catalan_G

Y

    Num.Y()

Returns the Euler–Mascheroni constant: 0.5772156649...

Aliases: γ, euler_gamma

|

    a | b

Returns the bitwise OR or a and b.

Aliases: or

~

    ~a
    a.not

Returns the bitwise NOT of a.

Aliases: not

Γ

    Γ(n)
    gamma(n)

The gamma function, where for any positive integer n:

    gamma(n) = (n-1)!

Aliases: gamma

δ

    δ(a,b)

The Kronecker delta function, which returns 1 iff a==b and 0 otherwise.

Aliases: kronecker_delta

ζ

    ζ(s)
    zeta(s)

The Riemann Zeta function.

Aliases: zeta

η

    η(s)
    eta(s)

The Dirichlet eta function, defined as:

    eta(s) = (1 - 2^(1-s)) * zeta(s)

Aliases: eta

μ

    μ(n)
    mu(n)
    moebius(n)

The Möbius function: μ(n).

Aliases: mu, mobius, möbius, moebius

Π

    Π(...)
    prod(...)

Returns the product of a given list of numbers.

Aliases: prod

π

    π(n)
    π(a,b)
    Num.π

Returns the PI numerical value:

    say Num.pi      #=> 3.1415...

When applied on a Number object (as n.pi or pi(n)), it returns the number of primes <= n:

    say 100.pi      #=> number of primes <= 100
    say pi(100)     #=> 25

When an additional argument is given, it returns the number of primes in the range a..b:

    say pi(50, 100)     # number of primes in the range 50..100

Aliases: pi

Σ

    Σ(...)
    sum(...)

Returns the sum of a given list of numbers.

Aliases: sum

σ

    σ(n,k=1)
    sigma(n,k=1)

Returns the sum of the positive divisors of n, each raised to the power k.

Aliases: sigma

τ

    Num.τ
    Num.tau

    τ(n)
    tau(n)

Returns the TAU constant (2*PI), or the number of positive divisors of n.

    say Num.tau     #=> 6.283185307179...
    say tau(120)    #=> 16

Aliases: tau

φ

    Num.φ
    Num.phi

    φ(n)
    phi(n)

Returns the golden ratio constant PHI, or the Euler totient of n.

    say Num.phi       #=> 1.618033988749...
    say phi(180)      #=> 48

Aliases: phi

Ψ

    Ψ(x)
    digamma(x)

The digamma function, defined as:

     Γ'(x)
    -------
     Γ(x)

Aliases: digamma

Ω

    Ω(n,k=0)
    bigomega(n,k=0)

For k = 0, it returns the number of prime factors of n (counted with multiplicity).

In general, is equivalent with:

    n.prime_power_divisors.sum {|d| n**k / d**k }

Aliases: bigomega

ω

    ω(n,k=0)
    omega(n,k=0)

For k = 0, it returns the number of distinct prime factors of n.

In general, is equivalent with:

    n.prime_divisors.sum {|d| n**k / d**k }

Aliases: omega

    a ≅ b

Returns true if a and b are approximately equal to each other.

Aliases: =~=, approx_eq

    a ≠ b

Returns true if a and b are different from each other.

Aliases: !=, ne

    a ≤ b

Returns true if a is less than or equal to b.

Aliases: <=, le

    a ≥ b

Returns true if a is greater than or equal to b.

Aliases: >=, ge

abs

    n.abs

The absolute value of n.

abundancy

    abundancy(n)

Returns the abundancy index of n, defined as:

    sigma(n)/n

Aliases: abundancy_index

acmp

    acmp(a,b)

Absolute comparison of a and b, defined as:

    abs(a) <=> abs(b)

acos

    n.acos

Inverse cosine of n in radians.

acosh

    n.acosh

Inverse hyperbolic cosine of n.

acot

    n.acot

Inverse cotangent of n in radians.

acoth

    n.acoth

Inverse hyperbolic cotangent of n.

acsc

    n.acsc

Inverse cosecant of n in radians.

acsch

    n.acsch

Inverse hyperbolic cosecant of n.

addmod

    addmod(a, b, m)

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

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

agm

    agm(a, b)

Arithmetic-geometric mean of a and b.

ai

    x.ai
    Ai(x)

Airy function of the first kind: Ai(x).

Aliases: airy

all_composite

    all_composite(...)

Returns true if all the given values are composite positive integers, by checking first for small factors, then running a B-PSW primality test.

all_prime

    all_prime(...)

Returns true if all the given values are prime numbers.

This is done by first running a primality pre-test on all values and returning early if one of the values is composite with a small factor. Otherwise, we run a B-PSW primality test on each value.

almost_prime_divisors

    n.almost_prime_divisors
    n.almost_prime_divisors(k)

Returns the k-almost prime divisors of n.

    say 5040.almost_prime_divisors(7)   #=> [720, 1008, 1680, 2520]

When k is omitted, an array of arrays with the k-almost prime divisors of n, for each k in the range 0..bigomega(n), is returned:

    say 120.almost_prime_divisors       #=> [[1], [2, 3, 5], [4, 6, 10, 15], [8, 12, 20, 30], [24, 40, 60], [120]]

almost_primes

    k.almost_primes(n)
    k.almost_primes(a,b)

Return an array with the k-almost primes <= n, or in the range a..b.

    5.almost_primes(1e6)        # array of 5-almost primes <= 1e6
    5.almost_primes(1e5, 1e6)   # array of 5-almost primes in the range [1e5, 1e6]

approx_ge

    approx_ge(a, b)
    approx_ge(a, b, k)

True if a is approximately greater than or equal to b.

Equivalent with:

    a.round(k) >= b.round(k)

approx_gt

    approx_gt(a, b)
    approx_gt(a, b, k)

True if a is approximately greater than b.

Equivalent with:

    a.round(k) > b.round(k)

approx_le

    approx_le(a, b)
    approx_le(a, b, k)

True if a is approximately less than or equal to b.

Equivalent with:

    a.round(k) <= b.round(k)

approx_lt

    approx_lt(a, b)
    approx_lt(a, b, k)

True if a is approximately less than b.

Equivalent with:

    a.round(k) < b.round(k)

approx_ne

    approx_ne(a, b)
    approx_ne(a, b, k)

True if a is approximately different than b.

Equivalent with:

    a.round(k) != b.round(k)

as_bin

    n.as_bin

Returns a String with the binary representation of n.

    say 42.as_bin     # "101011"

as_dec

    n.as_dec
    n.as_dec(k)

Given a rational number n, it returns its decimal expansion as a String object, expanded at k decimal places.

    say (1/17 -> as_dec(10))      # 0.05882352941
    say (1/17 -> as_dec(30))      # 0.0588235294117647058823529411765

Aliases: as_float

asec

    n.asec

Inverse secant of n in radians.

asech

    n.asech

Inverse hyperbolic secant of n.

as_frac

    n.as_frac
    n.as_frac(base)

String-representation of n as fraction.

    say 24.as_frac                 # 24/1
    say bernoulli(10).as_frac      # 5/66
    say bernoulli(12).as_frac(36)  # -j7/23u

If n is an integer, it uses 1 for the denominator.

as_hex

    n.as_hex

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

    say 42.as_hex       # "2a"

Returns nil when n cannot be converted to an integer.

asin

    n.asin

Inverse sine of n in radians.

asinh

    n.asinh

Inverse hyperbolic sine of n.

as_int

    n.as_int
    n.as_int(base)

Returns a String representing the integer part of n in a given base, where the base must be between 2 and 62.

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

    say 255.as_int      # "255"
    say 255.as_int(16)  # "ff"

Returns nil when n cannot be converted to an integer.

as_oct

    n.as_oct

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

    say 42.as_oct   # 52

Returns nil when n cannot be converted to an integer.

as_rat

    n.as_rat
    n.as_rat(base)

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

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

    say as_rat(42)          # "42"
    say as_rat(2/4)         # "1/2"
    say as_rat(255, 16)     # "ff"

Returns nil when n cannot be converted to a rational number.

atan

    n.atan

Inverse tangent of n in radians.

atan2

    atan2(a, b)

Four-quadrant inverse tangent of a and b.

atanh

    n.atanh

Inverse hyperbolic tangent of n.

base

    n.base(b)

Returns a String-representation of n in a given base b, which must be between 2 and 62.

Aliases: in_base

bdivisors

    bdivisors(n)

Returns an array with the bi-unitary divisors of n.

    say 48.bdivisors    #=> [1, 2, 3, 6, 8, 16, 24, 48]

These are divisors d of n that satisfy:

    gcud(n/d, d) = 1

Aliases: biudivisors, bi_unitary_divisors

bell

    n.bell

Returns the n-th Bell number.

Aliases: bell_number

bellmod

    bellmod(n, m)

Returns the n-th Bell number modulo m.

For large n > 1000, this is faster than:

    bell(n) % m

bern

    n.bern
    bernoulli(n)
    bernoulli(n, x)

Returns the n-th Bernoulli number. When an additional argument is provided, it returns the n-th Bernoulli polynomial evaluated at x.

    say bernoulli(10).as_rat       # B_10    = 5/66
    say bernoulli(10, 2).as_rat    # B_10(2) = 665/66

Aliases: bernfrac, bernoulli, bernoulli_number

bernoulli_polynomial

    bernoulli_polynomial(n)
    bernoulli_polynomial(n, x)

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

When x is omitted, a Polynomial object is returned.

bernreal

    n.bernreal

Return an approximation to the n-th Bernoulli number as a floating-point number.

bessel_j

    bessel_j(x, n)

First order Bessel function: J_n(x).

bessel_y

    bessel_y(x, n)

Second order Bessel function: Y_n(x).

beta

    beta(a, b)

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

Defined as:

    beta(a, b) = gamma(a)*gamma(b) / gamma(a+b)

binomialmod

    binomialmod(n, k, m)

Returns the binomial coefficient binomial(n,k) modulo m, computed efficiently.

    say binomialmod(1e10, 1e5, 20!)     #=> 286953611424480000

Equivalent with (but much faster):

    binomial(n,k) % m

bit

    n.bit(k)
    n.getbit(k)

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

Return nil when n cannot be truncated to an integer or when k is negative.

    say getbit(0b1001, 0)   # 1
    say getbit(0b1000, 0)   # 0

Aliases: getbit, testbit

bits

    n.bits()

Returns the binary digits of n.

The bits are ordered from the most significant bit to the least significant bit.

    say 1234.bits       #=> [1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0]

Equivalent with:

    n.digits(2).flip

bit_scan0

    n.bit_scan0
    n.bit_scan0(k)

Scan n, starting from bit index k, towards more significant bits, until a 0-bit is found.

When k is omitted, k=0 is assumed.

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

bit_scan1

    n.bit_scan1
    n.bit_scan1(k)

Scan n, starting from bit index k, towards more significant bits, until a 1-bit is found.

When k is omitted, k=0 is assumed.

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

bsearch

    bsearch(n, {...})
    bsearch(a, b, {...})

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

The last argument is a block which does the comparisons.

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

    say bsearch(20,      {|k| k*k  <=> 49   })   #=> 7   (7*7  = 49)
    say bsearch(3, 1000, {|k| k**k <=> 3125 })   #=> 5   (5**5 = 3125)

bsearch_ge

    bsearch_ge(n, {...})
    bsearch_ge(a, b, {...})

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

The last argument is a block which does the comparisons.

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

    bsearch_ge(1e6,       { .exp <=> 1e+9 })  #  21   (exp( 21) >= 1e+9)
    bsearch_ge(-1e6, 1e6, { .exp <=> 1e-9 })  # -20   (exp(-20) >= 1e-9)

bsearch_le

    bsearch_le(n, {...})
    bsearch_le(a, b, {...})

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

The last argument is a block which does the comparisons.

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

    bsearch_le(1e6,       { .exp <=> 1e+9 })  #  20   (exp( 20) <= 1e+9)
    bsearch_le(-1e6, 1e6, { .exp <=> 1e-9 })  # -21   (exp(-21) <= 1e-9)

bsearch_max

    bsearch_max(n, {...})
    bsearch_max(a,b, {...})

Binary search, returning the largest integer value in the range a..b that satisfies the given comparison function.

    say bsearch_max(1, 1e6, {|k| pi(k) <=> 100 })   #=> 546

where:

    n = 546 is the  largest value satisfying pi(n) <= 100

bsearch_min

    bsearch_min(n, {...})
    bsearch_min(a,b, {...})

Binary search, returning the smallest integer value in the range a..b that satisfies the given comparison function.

    say bsearch_min(1, 1e6, {|k| pi(k) <=> 100 })   #=> 541

where:

    n = 541 is the smallest value satisfying pi(n) >= 100

bsearch_solve

    bsearch_solve(n, {...})
    bsearch_solve(a,b, {...})

It computes the inverse of any continuous function, given the range that includes the inverse value.

For floating-point values, the approx_cmp(a,b) method (or the `<~>` operator) is recommended to be used for comparisons.

    say bsearch_inverse(100, {|x| exp(x) <~> 2 })          # solution to x for: exp(x) =   2
    say bsearch_inverse(200, {|x| x**2  <=> 43 })          # solution to x for:    x^2 =  43
    say bsearch_inverse(-10, 10, {|x| x**3 <~> -43 })      # solution to x for:    x^3 = -43
    say bsearch_inverse(300, 500, {|x| Li(x) <~> 100 })    # solution to x for:  Li(x) = 100

This method can also be used in computing approximations to some integer-specific functions:

    var n = 100000
    var v = 2*int(n*log(n) / log(log(n)))

    say nth_semiprime(n)                                        #=> 459577
    say bsearch_inverse(v, {|x| semiprime_count(x) <=> n })     #=> 459577.93302154541015625

Aliases: bsearch_inverse

bsigma

    bsigma(n, k=1)

Returns the sum of the bi-unitary divisors of n, each divisor raised to the k-th power.

    say 20.of { .bsigma }   #=> OEIS: A188999

Aliases: biusigma

bsigma0

    bsigma0(n)

Returns the count of the bi-unitary divisors of n.

    say 20.of { .bsigma0 }  #=> OEIS: A286324

Aliases: biusigma0

by

    n.by { ... }

Returns an array with n elements >= 0 that satisfy the provided block of code.

    say 10.by { .is_prime }      # first 10 primes
    say 10.by { .is_square }     # first 10 squares

Aliases: first

cadd

    cadd(a,b,x,y)

Complex arithmetic addition, defined as:

    cadd(a,b,x,y)   #=> (a+x, b+y)

Aliases: complex_add

catalan

    n.catalan
    n.catalan(k)

Returns the n-th Catalan number.

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

cbrt

    n.cbrt

Cube root of n, as a floating-point value.

cdiv

    cdiv(a,b,x,y)

Complex arithmetic division, defined as:

    cdiv(a,b,x,y)   #=> ((a*x + b*y)/(x*x + y*y), (b*x - a*y)/(x*x + y*y))

Aliases: complex_div

ceil

    n.ceil

Round n towards positive Infinity.

Aliases: ceiling

cfrac

    n.cfrac
    n.cfrac(k)

Compute k terms of the simple continued-fraction expansion of n.

    say sqrt(12).cfrac(6)    # [3, 2, 6, 2, 6, 2, 6]

Can also be used to compute very good rational approximations to a given real number:

    say Num.pi.cfrac(10).flip.reduce{|a,b| b + 1/a }.as_rat      # 4272943/1360120

When k is omitted, it uses the default floating-point precision to deduce k.

Aliases: as_cfrac

chebyshev_factor

    n.chebyshev_factor
    n.chebyshev_factor(B)
    n.chebyshev_factor(B,x)

Integer factorization method, based on Chebyshev polynomials, which have the following nesting property:

    T_{m n}(x) = T_m(T_n(x))

which are efficiently computed using the Lucas V function V_n(P,Q):

    T_n(x) = (1/2) * V_n(2x, 1)

This method is particularly effective for numbers that have a prime factor p such that p-1 or p+1 is B-smooth.

    say chebyshev_factor(1124075136413 * 3556516507813, 4000, 3)

The product of the factors, will give back n. However, some factors may be composite.

chebyshevT

    chebyshevT(n)
    chebyshevT(n, x)

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)

When x is omitted, a Polynomial object is returned.

Aliases: chebyshevt

chebyshevTmod

    chebyshevTmod(n, x, m)

Compute the modular Chebyshev polynomials of the first kind: T_n(x) mod m, where n and m must be integers (arbitrarily large).

chebyshevU

    chebyshevU(n)
    chebyshevU(n, x)

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)

When x is omitted, a Polynomial object is returned.

Aliases: chebyshevu

chebyshevUmod

    chebyshevUmod(n, x, m)

Compute the modular Chebyshev polynomials of the second kind: U_n(x) mod m, where n and m must be integers (arbitrarily large).

chr

    n.chr

Convert the integer n into a character.

    say 97.chr      # "a"
    say 9786.chr    # "☺"

cinv

    cinv(a,b)

Complex arithmetic inversion, defined as:

    cinv(a,b)   #=> (a/(a*a + b*b), (-b)/(a*a + b*b))

Aliases: complex_inv

cinvmod

    cinvmod(a,b,m)

Complex modular inversion modulo m: returns a pair of integers (x,y) such that:

    cmod(cmul(a,b,x,y), m) == (1, 0)

Aliases: complex_invmod

circular_permutations

    n.circular_permutations
    n.circular_permutations { ... }

Returns an array of arrays with the circular permutations of the integers in the range 0..n-1, or iterates over the circular permutations when a block is given.

    5.circular_permutations {|*a| say a }

cis

    cis(x)

Euler's formula applied on x, defined as:

    cis(x) = cos(x) + sin(x)*i

clearbit

    n.clearbit(k)

Set the k-th bit of integer n to 0.

    say clearbit(0b1001, 0).as_bin  #=> 1000
    say clearbit(0b1100, 2).as_bin  #=> 1000

cmod

    cmod(a,b,m)

Complex arithmetic modular operation, defined as:

    cmod(a,b,m)     #=> (a%m, b%m)

Aliases: complex_mod

cmul

    cmul(a,b,x,y)

Complex arithmetic multiplication, defined as:

    cmul(a,b,x,y)   #=> (a*x - b*y, a*y + b*x)

Aliases: complex_mul

combinations

    n.combinations(k)
    n.combinations(k, { ... })

Returns an array with the k-combinations of the integers in the range 0..n-1, or iterates over the k-combinations when a block is given.

    5.combinations(2, {|*a| say a })

combinations_with_repetition

    n.combinations_with_repetition(k)
    n.combinations_with_repetition(k, { ... })

Returns an array with the k-combinations with repetition of the integers in the range 0..n-1, or iterates over the k-combinations with repetition when a block is given.

    5.combinations_with_repetition(2, {|*a| say a })

commify

    n.commify

Returns a string with thousands separators added after each group of 3 decimal digits.

Exmaple:

    say 1000.commify       #=> 1,000
    say 1e10.commify       #=> 10,000,000,000

complex

    n.complex
    complex(a,b)

Converts n to a complex number, or creates a complex number from a and b.

    say complex(3, 4)       #=> 3+4i

This is equivalent with:

    say Complex(3, 4)       #=> 3+4i

complex_cmp

    complex_cmp(a,b,x,y)

Complex number comparison, defined as:

    (a <=> x) || (b <=> y)

complex_ipow

    complex_ipow(a,b,n)

Complex integer exponentiation: returns (x,y) such that x+y*i = (a+b*i)^n.

    say [complex_ipow(3,4,5)]       #=> [-237, -3116]

composite

    n.composite

Returns the n-th composite number (OEIS: A002808).

    say composite(10**9)        #=> 1053422339

Aliases: nth_composite

composite_count

    composite_count(n)
    composite_count(a,b)

Returns the number of composite numbers <= n, or in the range a..b.

    say composite_count(100)          # number of composites <= 100
    say composite_count(50, 100)      # number of composites in the range 50..100

composites

    composites(n)
    composites(a,b)

Returns an array with the composite numbers <= n, or in the range a..b.

conj

    conj(x)

Complex conjugate of x. For real integers, this is a fixed-point function.

consecutive_lcm

    consecutive_lcm(n)

Returns the least common multiple (LCM) of all the integers in the range 1..n.

Aliases: consecutive_integer_lcm

convergents

    n.convergents(k)

Returns an array with the continued fraction convergents for a given real number n, where k is the number of convergenents to be computed and returned.

    say Num.pi.convergents(5)   #=> [3, 22/7, 333/106, 355/113, 103993/33102]

cop_factor

    cop_factor(n, tries=n.ilog2)

Congruence of Powers (CoP) factorization method, trying to find algebraic factors of n.

    say cop_factor((5**48 + 1)*(3**120 + 1))

An additional argument can be given to limit the number of iterations.

The product of the factors, will give back n. However, some factors may be composite.

core

    core(n)

Squarefree part of n.

    say 30.of { .core }     #=> OEIS: A007913

Equivalent to PARI/GP core(n) function.

Aliases: squarefree_part

cos

    cos(x)

Trigonometric cosine function.

cosh

    cosh(x)

Hyperbolic cosine function.

cot

    cot(x)

Trigonometric cotangent function.

coth

    coth(x)

Hyperbolic cotangent function.

cpow

    cpow(a,b,n)

Computes (a + b*i)^n, where a,b are real numbers and n is an integer. Returns the real and imaginary part as a list.

    say [cpow(3, 4, 10)]    #=> [-9653287, 1476984]

Aliases: complex_pow

cpowmod

    cpowmod(a,b,n,m)

Efficiently computes (a + b*i)^n mod m, where a,b,n,m are all integers. Returns the real and imaginary part as a list.

    say [complex_powmod(3, 4, 1000, 1e6)]   #=> [585313, 426784]

Aliases: complex_powmod

csc

    csc(x)

Trigonometric cosecant function.

csch

    csch(x)

Hyperbolic cosecant function.

csub

    csub(a,b,x,y)

Complex arithmetic subtraction, defined as:

    csub(a,b,x,y)   #=> (a-x, b-y)

Aliases: complex_sub

cube

    cube(x)

Returns the cube of x. Equivalent with x**3.

cubic_formula

    cubic_formula(a, b, c, d)

Returns a list of (complex) solutions (x_1, x_2, x_3) to the cubic equation:

    a*x^3 + b*x^2 + c*x + d = 0

cyclotomic

    cyclotomic(n)
    cyclotomic(n,x)

Returns the n-th Cyclotomic polynomial evaluated at x.

    say cyclotomic(12, 10)      #=> 9901

When x is omitted, a Polynomial object is returned:

    say cyclotomic(12)          #=> x^4 - x^2 + 1

Aliases: cyclotomic_polynomial

cyclotomicmod

    cyclotomicmod(n, x, m)

Returns the n-th Cyclotomic polynomial evaluated at x, computed modulo m.

    say cyclotomicmod(30!, 5040, 2**128 + 1)

It returns NaN when moebius(d) = -1 and gcd(n/d, m) != 1, for some d|n.

dconv

    n.dconv(f,g)

Returns the Dirichlet convolution of f and g.

    say 20.of { .dirichlet_convolution({.moebius}, {_}) }

Aliases: dirichlet_convolution

de

    r.de
    r.denominator

Returns the denominator for a rational number r.

    say denominator(43/97)      #=> 97

Aliases: denominator

defs

    n.defs { ... }

Returns an array with the first n defined values returned by the given block. The block is called with k = 0,1,...

    10.defs {|k| k.is_prime ? k+1 : nil }      # array of p+1 for the first 10 primes p

deg2rad

    deg2rad(x)

Convert degrees to radians.

    say deg2rad(180)    #=> 3.14159...

derangements

    n.derangements

Returns an array of arrays with the derangements of the integers in the range 0..n-1, or iterates over the derangements when a block is given.

    5.derangements {|*a| say a }

Aliases: complete_permutations

derivative

    derivative(n)

Arithmetic derivative of n, defined for rationals and integers (positive and negative).

    say derivative(5040)                 #=> 15168
    say derivative(-5040/4323).as_frac   #=> -6240176/2076481

Aliases: arithmetic_derivative

difference_of_squares

    difference_of_squares(n)

Returns an array of [a,b] pairs with all the possible solutions to the equation: a^2 - b^2 = n.

    say difference_of_squares(48)   #=> [[7, 1], [8, 4], [13, 11]]

digit

    n.digit(k, b=10)

Returns the k-th digit of n in a base b.

Exmaples:

    say 1119.digit(0)         #=> 9
    say 1181.digit(1)         #=> 8
    say 1711.digit(2)         #=> 7
    say 6111.digit(3)         #=> 6
    say 1234.digit(4)         #=> 0

It also supports negative indices:

    say 9111.digit(-1)        #=> 9
    say 1811.digit(-2)        #=> 8
    say 1234.digit(-42)       #=> nil

digital_root

    digital_root(n, b=10)

Returns the digital root of n, with respect to base b.

    say 30.of { .digital_root }               #=> OEIS: A010888
    say 30.of { .digital_root(.isqrt+1) }     #=> OEIS: A122197

Also known as "repeated digital sum".

Both n and b can be arbitrary large, as long as b > 1.

digits

    n.digits(b=10)

Returns the digits of n in base b, ordered from the least significant digit to the most significant digit.

    say 1234.digits      #=> [4,3,2,1]
    say 1234.digits(20)  #=> [14, 1, 3]

The reverse operation is:

    b.digits2num(n.digits(b)) == n

digits2num

    b.digits2num(digits)

Convert an array of digits to a number in the base b.

The array of digits are ordered from the least significant digit to the most significant digit, as returned by n.digits(b).

    say 10.digits2num([4,3,2,1])  #=> 1234

Aliases: from_digits

digits_sum

    sumdigits(n, b=10)

Sum of base b digits of n.

    say sumdigits(1234)         #=> 10
    say sumdigits(1e5!, 100)    #=> 10658934

This is equivalent to:

    n.digits(b).sum

Aliases: sum_digits, sumdigits

dirichlet_sum

    n.dirichlet_sum(f, g, F, G)

The method computes the following sum in O(sqrt(n)) steps:

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

Where F and G are the partial sums of f and g, respectively.

    say dirichlet_hyperbola(1e3,
            { .is_squarefree ? 1 : 0 },
            { _*_ },
            { .squarefree_count },
            { .faulhaber(2) }
    )

Aliases: dirichlet_hyperbola

divides

    a.divides(b)
    a `divides` b

Returns true if a divides b.

    say 3.divides(15)   #=> true

divisor_map

    n.divisor_map {|d| ... }

Maps the divisors of n to the given block.

    say 24.divisor_map {|d| 1/d }  #=> [1, 1/2, 1/3, 1/4, 1/6, 1/8, 1/12, 1/24]

divisor_prod

    n.divisor_prod {|d| ... }

Product of the mapping of the positive divisors of n.

Equivalent with:

    n.divisor_map {|d| ... }.prod

Aliases: divisors_prod

divisors

    n.divisors(k=n)

Return an array with the positive divisors of n <= k.

    say 120.divisors        #=> [1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120]
    say 120.divisors(13)    #=> [1, 2, 3, 4, 5, 6, 8, 10, 12]

divisor_sum

    n.divisor_sum {|d| ... }

Sum of the mapping of the positive divisors of n.

    say 5040.divisor_sum {|d| euler_phi(d)**2 } #=> 2217854

Equivalent with:

    n.divisor_map {|d| ... }.sum

Aliases: divisors_sum

divmod

    divmod(a, b)
    divmod(a, b, m)

When only two arguments are provided, it returns (a//b, a%b).

    say [divmod(23, 10)]    #=> [2,3]

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

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

dop_factor

    dop_factor(n, tries=n.ilog2)

Difference of Powers (DoP) factorization method, trying to find algebraic factors of n.

    say dop_factor(2**120 + 1)

An additional argument can be given to limit the number of iterations.

The product of the factors, will give back n. However, some factors may be composite.

downto

    a.downto(b, step=1)

Returns a reverse range from a down to b, with an optional stepping value.

    say 10.downto(1)        #=> RangeNum(10, 1, -1)
    say 10.downto(1, 2)     #=> RangeNum(10, 1, -2)

dump

    n.dump

Returns a stringification version of n.

    say dump(42)    #=> "42"
    say dump(3/4)   #=> "3/4"

e

    Num.e

Returns the e mathematical constant: 2.71828...

each_almost_prime

    k.each_almost_prime(n, {...})
    k.each_almost_prime(a,b, {...})

Iterates over the k-almost prime numbers <= n, or in the range a..b.

    11.almost_primes_each(1e7, {|n| say n })        # iterate over 11-almost primes <= 1e6
    11.almost_primes_each(1e6, 1e7, {|n| say n })   # iterate over 11-almost primes in the range [1e6, 1e7]

Aliases: almost_primes_each

each_composite

    n.each_composite { ... }
    each_composite(a,b, { ... })

Iterate over the composite numbers <= n, or in the given range a..b.

    # Iterate over the composite integers between 100 and 200
    each_composite(100, 200, {|c|
        say c
    })

    # Iterate over the composite integers <= 100
    100.each_composite {|c|
        say c
    }

Aliases: composites_each

each_omega_prime

    k.omega_primes_each(n, { ... })
    k.omega_primes_each(a, b, { ... })

Iterates over the k-omega primes <= n, or in the range a..b.

k-omega primes are numbers n such that omega(n) == k.

    1.omega_primes_each(100, {|n| say n })          # iterate over prime powers <= 100
    2.omega_primes_each(50, 100, {|n| say n })      # iterate over 2-omega primes in range 50..100

Aliases: omega_primes_each

each_powerful

    k.powerful_each(n, { ... })
    k.powerful_each(a, b, { ... })

Iterates over the k-powerful numbers <= n, or in the range a..b.

    2.powerful_each(100, {|n| say n })          # iterate over 2-powerful numbers <= 100
    2.powerful_each(50, 100, {|n| say n })      # iterate over 2-powerful in the range 50..100

Aliases: powerful_each

each_prime

    n.each_prime {...}
    each_prime(a,b,{...})

It efficiently iterates over the primes in the given range, using a segmented prime sieve.

    # Iterate over the primes between 100 and 200
    each_prime(100, 200, {|p|
        say p
    })

    # Iterate over the primes <= 100
    100.each_prime {|p|
        say p
    }

It's considerably faster than using the next_prime(n) method.

Aliases: primes_each

each_semiprime

    n.each_semiprime { ... }
    each_semiprime(a,b, { ... })

Iterate over semiprimes <= n, or in the range a..b:

    100.each_semiprime {|k| say k }         # iterate over semiprimes <= 100
    each_semiprime(50, 100, {|k| say k })   # iterate over semiprimes in the range [50, 100]

Aliases: semiprimes_each

each_squarefree

    n.each_squarefree {...}
    each_squarefree(a,b,{...})

Iterates over the squarefree numbers in a given range.

    # Iterate over the squarefree numbers in the interval [100, 200]
    each_squarefree(100, 200, {|n|
        say n
    })

    # Iterate over the squarefree numbers <= 100
    100.each_squarefree {|n|
        say n
    }

Aliases: squarefree_each

each_squarefree_almost_prime

    k.each_squarefree_almost_prime(n, {...})
    k.each_squarefree_almost_prime(a,b,{...})

Iterates over the squarefree k-almost primes <= n, or in the range a..b.

    # Iterate over squarefree 3-almost primes <= 100
    3.squarefree_almost_primes_each(100, { .say })

    # Iterate over squarefree 3-almost primes in the range 50..100
    3.squarefree_almost_primes_each(50, 100, { . say })

Aliases: squarefree_almost_primes_each

ecm_factor

    n.ecm_factor
    n.ecm_factor(B1)
    n.ecm_factor(B1, curves)

Hendrik Lenstra's elliptic curve factorization method (ECM).

The product of the factors, will give back n. However, some factors may be composite.

edivisors

    edivisors(n)

Returns an array with the exponential divisors (or e-divisors) of n.

    say edivisors(5040)     #=> [210, 420, 630, 1260, 1680, 5040]

Aliases: exponential_divisors

ei

    ei(x)

Exponential integral function.

Aliases: eint

erf

    erf(x)

The Gauss error function.

erfc

    erfc(x)

The complementary error function.

esigma

    esigma(n, k=1)

Returns the sum of the exponential divisors (or e-divisors) of n, each divisor raised to k-th power.

    say 20.of { .esigma }       #=> OEIS: A051377

esigma0

    esigma0(n)

Returns the count of the exponential divisors (or e-divisors) of n.

    say 20.of { .esigma0 }      #=> OEIS: A049419

euler

    euler(n)
    euler(n,x)

Returns the n-th Euler number:

    say 10.of {|n| euler_number(n) }   #=> [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0]

Returns the n-th Euler polynomial evaluated at x, when x is given:

    say euler(10, 5)    #=> 1981100

Aliases: euler_number

euler_polynomial

    euler_polynomial(n)
    euler_polynomial(n, x)

Returns the n-th Euler polynomial evaluated at x.

When x is omitted, a Polynomial object is returned.

eval

    eval(x,v)

Returns back x.

exp

    exp(x)
    exp(b, x)

Exponential function: e^x.

When two arguments are given, it does floating-point exponentiation: b^x.

exp10

    exp10(x)

Exponential function: 10^x.

exp2

    exp2(x)

Exponential function: 2^x.

exp_mangoldt

    exp_mangoldt(n)

Returns exp(Λ(n)); the exponential of the Mangoldt function.

expmod

    powmod(b, n, m)

Modular exponentiation: b^n mod m, where b is an integer or a rational number and n and m are both integers.

    say powmod(2, 42, 43)           #=> 1
    say powmod(3/4, 1234, 4171)     #=> 2138

Aliases: powmod

expnorm

    expnorm(n, b=10)

Returns exp(n) normalized in the range [0,1).

    say expnorm(log(2) * 20996011)          #=> 0.125976895450330105020494309574...

    say exp(log(10!))               #=> 3628800
    say expnorm(log(10!))           #=> 0.36288
    say expnorm(log(10!), 2)        #=> 0.86517333984375

    say 3628800.base(2)             #=> 1101110101111100000000
    say 0.86517333984375.base(2)    #=> 11011101011111/100000000000000

Complex numbers are also supported:

    say expnorm(log(-1))            #=> 0.06682015101903....+0.074398033695749....i
    say expnorm(log(-1234)).abs     #=> 0.1234

factor

    factor(n)

Returns an array with the prime factors of n, where n is a positive integer, such that n.factor.prod == n.

    say 180.factor  #=> [2, 2, 3, 3, 5]

Aliases: factors

factor_exp

    factor_exp(n)

Returns an array of pairs [p,k] factors p^k of n.

    say 180.factor_exp  #=> [[2, 2], [3, 2], [5, 1]]

Aliases: factors_exp

factorialmod

    factorialmod(n,m)

Returns the factorial of n modulo m.

Equivalent with (but much faster):

    factorial(n) % m

factorial_power

    factorial_power(n, p)

Returns the number of times p divides n!, where p is a prime number.

Equivalent with (but more efficient):

    valuation(n!, p)

Aliases: factorial_valuation

factorial_sum

    factorial_sum(n)

Left factorial of n, defined as:

    Sum_{k=0..n-1} k!

Example:

    say 20.of { .factorial_sum }    # OEIS: A003422

Aliases: left_factorial

factor_map

    n.factor_map {|p,k| ... }

Maps the prime-power factorization (p,k) of n to the given block.

    say 5040.factor_map  {|p,k| p**k }  #=> [16, 9, 5, 7]

factor_prod

    n.factor_prod {|p,k| ... }

Product of the mapping of the prime-power factorization of n.

    say 5040.factor_prod {|p,k| (p-1) * p**(k-1) }  #=> 1152

Equivalent with:

    n.factor_map {|p,k| ... }.prod

Aliases: factors_prod

factor_sum

    n.factor_sum {|p,k| ... }

Sum of the mapping of the prime-power factorization of n.

Equivalent with:

    n.factor_map {|p,k| ... }.sum

Aliases: factors_sum

falling_factorial

    falling_factorial(n,k)

Falling factorial: (n)_k = 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.

faulhaber

    faulhaber(n,k)

Sum of powers: 1^k + 2^k + ... + n^k, using Faulhaber's summation formula.

    faulhaber(5, 2)   # 1^2 + 2^2 + 3^2 + 4^2 + 5^2 = 55

The value for k must be a non-negative native integer.

Aliases: faulhaber_sum

faulhaber_polynomial

    faulhaber_polynomial(n)
    faulhaber_polynomial(n, x)

Computes the n-th Faulhaber polynomials evaluated at x.

Defined in terms of the Bernoulli polynomials, as:

    faulhaber_polynomial(n,x) = (bernoulli_polynomial(n+1,x+1) - bernoulli_polynomial(n+1, 1))/(n+1)

When x is omitted, a Polynomial object is returned.

faulhaber_range

    faulhaber_range(a, b, k)

Sum of powers: a^k + (a+1)^k + (a+2)^k + ... + b^k, using Faulhaber's summation formula.

    faulhaber_range(50, 100, 2)   # 50^2 + 51^2 + ... + 100^2 = 297925

The value for k must be a non-negative native integer.

fermat_factor

    n.fermat_factor(k=1e4)

Tries to factorize a given number using Fermat's factorization method (using at most k iterations).

Works for odd composite non-power numbers n that have two divisors close to sqrt(n).

The product of the factors, will give back n. However, some factors may be composite.

fib

    fib(n)
    fib(n,k)

Returns the n-th Fibonacci number.

    say 10.of { .fib }      #=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

When an additional is provided, it returns the n-th Fibonacci number of k-th order.

    say 20.of { .fib(3) }   #=> Tribonacci numbers
    say 20.of { .fib(4) }   #=> Tetranacci numbers
    say 20.of { .fib(5) }   #=> Pentanacci numbers

Aliases: fibonacci

fibmod

    fibmod(n,m)

Efficiently compute the n-th Fibonacci number modulo m.

Aliases: fibonacci_mod, fibonaccimod

flip

    n.flip(base=10)

Returns the reversal of n in base b. When b is not given, it defaults to base 10.

    say 20.of { .flip }         # A004086
    say 20.of { .flip(2) }      # A030101

Aliases: reverse

flipbit

    flipbit(n,k)

Flip the value of the k-th bit of integer n.

    say flipbit(0b1000, 0).as_bin  #=> 1001
    say flipbit(0b1001, 0).as_bin  #=> 1000

floor

    floor(x)

Round x towards -Infinity.

    say floor( 2.5)     #  2
    say floor(-2.5)     # -3

flt_factor

    n.flt_factor(base=2, tries=1e4)

Tries to find a factor of n, using a new factorization method, inspired by Fermat's Little Theorem (FLT).

This method is particularly effective for numbers that have factors closed to each other, or have a factor k for which znorder(2,k) is small.

Example (try with base 3 and give up after 10^6 iterations):

    say flt_factor(2**64 + 1, 3, 1e6)   #=> [274177, 67280421310721]

The product of the factors, will give back n. However, some factors may be composite.

fusc

    fusc(n)

Returns the n-th term in Stern's diatomic series (or Stern-Brocot sequence).

    say 30.of { .fusc }     #=> OEIS: A002487

gcd

    gcd(...)

Returns the greatest common divisor of a list of integers.

gcdext

    gcdext(a,b)

The extended greatest common divisor of a and b, returning (u, v, d), where d = gcd(a,b), while u and v are the coefficients satisfying:

    u*a + v*b = d.

The value of d is always non-negative.

gcud

    gcud(...)

Returns the greatest common unitary divisor of a list of integers.

geometric_sum

    geometric_sum(n,r)

Geometric sum: r^0 + r^1 + ... + r^n, using the following formula:

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

Example:

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

gpf

    gpf(n)

Returns the greatest prime factor of n.

Defined with the base-cases:

    gpf(0) = 0
    gpf(1) = 1

Example:

    say gpf(2**128 + 1)     #=> 5704689200685129054721

hamdist

    hamdist(a,b)

Returns the Hamming distance (number of bit-positions where the bits differ) between integers a and b.

harm

    harmonic(n)
    harmonic(n, k)

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.

When an additional argument is given, it returns the n-th Harmonic number of the k-th order.

Aliases: harmfrac, harmonic, harmonic_number

harmreal

    harmreal(n)
    harmreal(n, k)

Returns the n-th Harmonic number H_n as a floating-point value, defined as:

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

where γ is the Euler-Mascheroni constant.

When an additional argument is given, it returns the n-th Harmonic number of the k-th order.

hclassno

    hclassno(n)

Returns the Hurwitz-Kronecker class number.

    say 30.of { .hclassno.nu }      # OEIS: A058305
    say 30.of { .hclassno.de }      # OEIS: A058306
    say 30.of { 12 * .hclassno }    # OEIS: A259825

hermiteH

    hermiteH(n)
    hermiteH(n, x)

Physicists' Hermite polynomials: H_n(x).

When x is omitted, a Polynomial object is returned.

Aliases: hermite_polynomialH

hermiteHe

    hermiteHe(n)
    hermiteHe(n, x)

Probabilists' Hermite polynomials: He_n(x).

When x is omitted, a Polynomial object is returned.

Aliases: hermite_polynomialHe

holf_factor

    n.holf_factor
    n.holf_factor(tries)

Hart's OLF method (variant of Fermat's method).

The product of the factors, will give back n. However, some factors may be composite.

hyperfactorial

    hyperfactorial(n)

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

hyperfactorial_ln

    hyperfactorial_ln(n)

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

Aliases: lnhyperfactorial, hyperfactorial_log

hypot

    hypot(x,y)

The value of the hypotenuse for catheti x and y, defined as:

    sqrt(x**2 + y**2)

Also defined for complex numbers.

i

    x.i

Multiplies x by the imaginary unit i.

    say 42.i         #=> 42i
    say 42i.i        #=> -42

iadd

    iadd(a,b)

Integer addition: a+b.

icbrt

    icbrt(n)

Integer cube root of n.

idiv_ceil

    idiv_ceil(a,b)

Integer division of integers a and b, rounded towards +Infinity.

When a and b are integers, this is equivalent with:

    ceil(a/b)

idivisors

    idivisors(n)

Returns an array with the infinitary divisors (or i-divisors) of n.

    say 96.idivisors        #=> [1, 2, 3, 6, 16, 32, 48, 96]

Aliases: infinitary_divisors

idiv_round

    idiv_round(a,b)

Integer division of integers a and b, rounded towards nearest integer.

When a and b are integers, this is equivalent with:

    floor(a/b + 1/2)

idiv_trunc

    idiv_trunc(a,b)

Integer division of integers a and b, rounded towards 0.

When a and b are integers, this is equivalent with:

    trunc(a/b)

ilog

    ilog(n,b)

Integer logarithm of n to base b, satisfying:

    b**ilog(n,b) <= n < b**(ilog(n,b)+1)

ilog10

    ilog10(n)

Integer logarithm of n to base 10, equivalent to:

    ilog(n,10)

ilog2

    ilog2(n)

Integer logarithm of n to base 2, equivalent to:

    ilog(n,2)

im

    x.im

The imaginary part of complex number x. Return 0 when x is a real number.

Aliases: imag, imaginary

imod

    imod(a,m)

Integer remainder of a when divided by m: a % m.

imul

    imul(a,b)

Integer multiplication: a*b.

inf

    Num.inf

Returns the positive Infinity special floating-point value.

int

    int(x)
    trunc(x)

Truncate x to an integer.

Aliases: to_i, to_int, trunc

inv

    inv(x)

Multiplicative inverse of x: 1/x.

inverse_phi

    n.inverse_phi

Returns all the solutions x to the Euler totient function: phi(x) = n.

Aliases: inverse_totient

inverse_phi_len

    n.inverse_phi_len

Returns the number of solutions to the Euler totient function: phi(x) = n.

Equivalent with:

    n.inverse_phi.len

Aliases: inverse_totient_len

inverse_phi_max

    n.inverse_phi_max

Returns the largest solution x to the Euler totient function: phi(x) = n.

Equivalent with:

    n.inverse_phi.max

Returns nil if there are no solutions.

Aliases: inverse_euler_phi_max

inverse_phi_min

    n.inverse_phi_min

Returns the smallest solution x to the Euler totient function: phi(x) = n.

Equivalent with:

    n.inverse_phi.min

Returns nil if there are no solutions.

Aliases: inverse_euler_phi_min

inverse_polygonal

    polygonal_inverse(n)

Returns an array of pairs [r,k] such that polygonal(r,k) = n.

    say polygonal_inverse(4012)   #=> [[2, 4012], [4, 670], [8, 145], [4012, 2]]

Aliases: polygonal_inverse

inverse_psi

    n.inverse_psi

Returns all the solutions x to the Dedekin psi function: psi(x) = n.

    say inverse_psi(120)    #=> [75, 76, 87, 95]

Aliases: inverse_dedekind_psi

inverse_psi_len

    n.inverse_psi_len

Returns the number of solutions to Dedekind's psi function: psi(x) = n.

Equivalent to n.inverse_psi.len, but much faster.

Aliases: inverse_dedekind_psi_len

inverse_psi_max

    n.inverse_psi_max

Returns the largest solution x to the Dedekind psi function: psi(x) = n.

Equivalent with:

    n.inverse_psi.max

Returns nil if there are no solutions.

Aliases: inverse_dedekind_psi_max

inverse_psi_min

    n.inverse_psi_min

Returns the smallest solution x to the Dedekind psi function: psi(x) = n.

Equivalent with:

    n.inverse_psi.min

Returns nil if there are no solutions.

Aliases: inverse_dedekind_psi_min

inverse_sigma

    n.inverse_sigma(k=1)

The method returns all the numbers m for which sigma(m,k) = n, where n is given.

    say inverse_sigma(42)           # [20, 26, 41]
    say inverse_sigma(22100, 2)     # [120, 130, 141]

Also works with arbitrary large integers:

    say inverse_sigma(9325257382230393314439814176)

inverse_sigma_len

    n.inverse_sigma_len(k=1)

Returns the number of solutions to the sigma sum of divisors function: sigma_k(x) = n.

Equivalent to n.inverse_sigma(k).len, but much faster.

inverse_sigma_max

    n.inverse_sigma_max

Returns the largest solution x to the sum of divisors function: sigma(x) = n.

Equivalent with:

    n.inverse_sigma.max

Returns nil if there are no solutions.

inverse_sigma_min

    n.inverse_sigma_min

Returns the smallest solution x to the sum of divisors function: sigma(x) = n.

Equivalent with:

    n.inverse_sigma.min

Returns nil if there are no solutions.

inverse_uphi

    n.inverse_uphi

Returns an array with all the solutions x to uphi(x) = n.

    say inverse_uphi(120)       #=> [121, 143, 144, 155, 164, 183, 220, 231, 240, 242, 286, 310, 366, 462]

inverse_usigma

    n.inverse_usigma

Returns an array with all the possible solutions for x in usigma(x) = n.

    say inverse_usigma(120)                         #=> [60, 87, 92, 95, 99]
    say inverse_usigma(5040).len                    #=> 38
    say inverse_usigma(5040).map { .usigma }.uniq   #=> [5040]

invmod

    n.invmod(m)

Returns the modular inverse of n modulo m.

ipolygonal_root

    ipolygonal_root(n,k)

First integer k-gonal root of n.

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

ipolygonal_root2

    ipolygonal_root2(n,k)

Second integer k-gonal root of n.

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

ipow

    ipow(b,n)

Integer exponentiation: b^n.

ipow10

    ipow10(n)

Integer exponentiation: 10^n.

ipow2

    ipow2(n)

Integer exponentiation: 2^n.

iquadratic_formula

    iquadratic_formula(a,b,c)

Returns a list of integer solutions (x_1, x_2) to the quadratic equation: a*x^2 + b*x + c = 0, defined as:

    floor((-b ± isqrt(b^2 - 4ac)) / (2a))

Example:

    say [iquadratic_formula(13, -42, -34)]  #=> [3, -1]

Aliases: integer_quadratic_formula

irand

    irand(n)
    irand(a,b)

Returns a pseudorandom integer in range 0..n (all inclusive), or in the range a..b (all inclusive).

If a is greater than b, the returned integer will be in the range b..a.

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

iroot

    n.iroot(k)

Integer k-th root of n.

irootrem

    n.irootrem(k)

Returns a list with the integer k-th root of n and k-th root remainder of n.

Equivalent with:

    (n.iroot(k), n - n.iroot(k)**k)

is_abs_euler_psp

    n.is_abs_euler_psp

Returns true if n is an absolute Euler pseudoprime: p-1 | (n-1)/2 for every p|n, where n is a squarefree composite integer.

    say 10.by { .is_abs_euler_psp }     #=> OEIS: A033181

Aliases: is_absolute_euler_psp

is_abundant

    n.is_abundant

Returns true when sigma(n) > 2*n.

is_aks_prime

    n.is_aks_prime

Return true if n passes the Agrawal-Kayal-Saxena (AKS) primality test.

is_almost_prime

    n.is_almost_prime(k=2)

Return true if n is a k-almost prime (i.e.: true iff n is the product of k not necessarily distinct primes).

Equivalently, k-almost primes are numbers n such that bigomega(n) == k.

    say 20.by { .is_almost_prime(1) }   # primes
    say 20.by { .is_almost_prime(2) }   # semiprimes
    say 20.by { .is_almost_prime(3) }   # 3-almost primes

is_between

    n.is_between(min, max)

Returns a true value when `n >= min` and `n <= max`.

is_bpsw_prime

    n.is_bpsw_prime()

Returns true if n passes the B-PSW primality test (extra-strong variant).

is_carmichael

    n.is_carmichael()

Returns true if is a Carmichael number.

is_chebyshev

    n.is_chebyshev()

Returns true if n is an odd composite Chebyshev pseudoprime, as defined by OEIS A175530.

Aliases: is_chebyshev_psp, is_chebyshev_pseudoprime

is_complex

    x.is_complex

Returns true if x is a complex number.

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

is_composite

    n.is_composite

Returns true if n is a positive > 1 composite number.

is_congruent

    n.is_congruent(a,m)

Returns true when n is congruent to a modulo m.

    say 99923.is_congruent(-2, 5)   #=> true
    say 99923.is_congruent(3, 5)    #=> true

Also defined for rationals, floats and complex numbers:

    say is_congruent(124, 1/4, 3/4) #=> true

is_coprime

    is_coprime(a,b)

Returns true if gcd(a,b) = 1.

is_cube

    n.is_cube

Return true if n is a cube number (if it can be written as b^3, for some integer b).

is_cyclic

    n.is_cyclic

Returns true when gcd(phi(n), n) = 1, where phi(n) is the Euler totient function.

    say 30.by { .is_cyclic }    # OEIS: A003277

is_ecpp_prime

    n.is_ecpp_prime

Return true if n can be proved prime using the Elliptic Curve Primality Proving algorithm.

iseed

    iseed(n)

Re-seed the irand() function. The value for n can be any arbitrary large integer.

is_euler_psp

    n.is_euler_psp(bases...)

Return true if n is an Euler-Jacobi pseudoprime, given a list of bases.

Aliases: is_euler_pseudoprime

is_even

    n.is_even

Returns true if n is an integer divisible by 2.

is_fib

    n.is_fib

Returns true if n is a Fibonacci number. False otherwise.

Aliases: is_fibonacci

is_fib_psp

    n.is_fib_psp(P=1, Q=-1)

Returns true if n passes the Lucas test to the U, using the parameters P and Q.

    say 10.by { .is_composite && .is_lucasU_psp }               # Fibonacci pseudoprimes
    say 10.by { .is_odd_composite && .is_lucasU_psp(2, -1) }    #=> OEIS: A327651

Aliases: is_lucasu_psp, is_lucasU_psp, is_fibonacci_psp, is_lucasU_pseudoprime, is_fibonacci_pseudoprime

is_frobenius_psp

    n.is_frobenius_psp(a,b)

Return true if n is a Frobenius probable prime with respect to the polynomial x^2 - ax + b.

Aliases: is_frobenius_pseudoprime

is_fundamental

    n.is_fundamental

Returns true if n is a fundamental discriminant.

is_gaussian_prime

    is_gaussian_prime(a,b)

Returns true if a+b*i is a Gaussian prime.

    say is_gaussian_prime(3, 4)       #=> false
    say is_gaussian_prime(13, 42)     #=> true

Provided by Math::Prime::Util::GMP >= 0.52.

isigma

    isigma(n, k=1)

Returns the sum of the infinitary divisors of n, each divisor raised to the k-th power.

    say 20.of { .isigma }       #=> OEIS: A049417

isigma0

    isigma0(n)

Returns the count of the infinitary divisors of n.

    say 20.of { .isigma0 }      #=> OEIS: A037445

is_imag

    x.is_imag

Returns true if x is an imaginary number.

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

is_imprimitive_carmichael

    n.is_imprimitive_carmichael

Returns true if n is an imprimitive Carmichael numbers, as defined by OEIS: A328935.

    say 325533792014488126487416882038879701391121.is_imprimitive_carmichael   # true

The method efficiently tries to factorize large Carmichael numbers, using the miller_factor(n) method.

is_inf

    x.is_inf

Returns true if x equals positive infinity (Inf).

is_int

    x.is_int

Returns true if x is an integer.

is_khashin_psp

    n.is_khashin_psp

Return true if n passes the Frobenius test of Sergey Khashin.

Aliases: is_khashin_pseudoprime, is_frobenius_khashin_psp, is_frobenius_khashin_pseudoprime

is_lucas

    n.is_lucas

Returns true if n is a Lucas number. False otherwise.

is_lucas_carmichael

    n.is_lucas_carmichael

Returns true if n is a Lucas-Carmichael number.

    say 10.by(:is_lucas_carmichael)                               # OEIS: A006972
    say is_lucas_carmichael(58735331016965175152455996272482303)  # true

is_lucas_psp

    n.is_lucas_psp

Return true if n is a Lucas pseudoprime.

Aliases: is_lucas_pseudoprime

is_lucasv_psp

    n.is_lucasv_psp(P=1, Q=-1)

Returns true if n passes the Lucas test to the V sequence, using the parameters P and Q.

    say 10.by { .is_composite && .is_lucasV_psp }               # Bruckman-Lucas pseudoprimes
    say 10.by { .is_odd_composite && .is_lucasV_psp(2, -1) }    #=> OEIS: A330276

Aliases: is_lucasV_psp, is_bruckman_lucas_psp, is_lucasV_pseudoprime, is_bruckman_lucas_pseudoprime

is_mersenne_prime

    is_mersenne_prime(p)

Returns true if 2^p - 1 is a Mersenne prime.

    say 607.is_mersenne_prime       # prints true; (2**607 - 1) is a Mersenne prime.

is_mone

    x.is_mone

Returns true if x equals -1.

is_nan

    x.is_nan

Returns true if x holds the Not-a-Number special value (NaN).

is_neg

    x.is_neg

Returns true if x is negative.

Aliases: is_negative

is_ninf

    x.is_ninf

Returns true if x equals negative infinity (-Inf).

is_nm1_prime

    n.is_nm1_prime

Return true if n can be proved prime using the factorization of n-1.

Aliases: is_pm1_prime, is_nminus1_prime

is_np1_prime

    n.is_np1_prime

Return true if n can be proved prime using the factorization of n+1.

Aliases: is_pp1_prime, is_nplus1_prime

is_ntf

    g.is_ntf(n)

Returns true if g is a non-trivial integer factor of n.

Equivalent with (assuming g and n are both integers):

    g.divides(n) && g.is_between(2, n-1)

Aliases: is_nontrivial_factor

is_odd

    n.is_odd

Returns true when n is an integer not divisible by 2.

is_odd_composite

    n.is_odd_composite

Returns true when n is an odd composite integer.

is_omega_prime

    n.is_omega_prime(k=2)

Return true if n is a k-omega prime (i.e.: true if n is divisible by exactly k different primes).

Equivalently, k-omega primes are numbers n such that omega(n) == k.

    say 20.by { .is_omega_prime(1) }   # prime powers
    say 20.by { .is_omega_prime(2) }   # numbers n such that omega(n) == 2

is_one

    n.is_one

Returns true when n equals 1.

is_over_psp

    n.is_over_psp

Returns true if n is an overpseudoprime to base b. Multiple bases can also be provided.

An overpseudoprime to base b is a also a strong Fermat pseudoprime to base b and a super-pseudoprime to base b, where znorder(b,n) == znorder(b,p) for every p|n.

    say 10.by { .is_composite && .is_over_psp }         # overpseudoprimes to base 2
    say 10.by { .is_composite && .is_over_psp(3) }      # overpseudoprimes to base 3

Aliases: is_over_pseudoprime, is_overpseudoprime

is_palindrome

    n.is_palindrome(b=10)

Returns true if the given number n is palindromic in the given base b. When no base is given, it defaults to 10.

    # Numbers that are palindromic in bases 2 and 10 (OEIS: A007632)
    say 1e6.range.grep{ .is_palindrome(2) && .is_palindrome(10) }

Aliases: is_palindromic

is_pell_lucas_psp

    n.is_pell_lucas_psp

It returns true if V_n(2, -1) = 2 (mod n).

    say 20.by { .is_pell_lucas_pseudoprime }                               #=> OEIS: A270342
    say 20.by { .is_pell_lucas_pseudoprime && .is_composite }              #=> OEIS: A335668
    say 20.by { .is_pell_lucas_pseudoprime && .is_composite && .is_odd }   #=> OEIS: A330276

Aliases: is_pell_lucas_pseudoprime

is_pell_psp

    n.is_pell_psp

These are odd numbers that satisfy:

    U_n(2, -1) = (2|n) (mod n)

Example:

    say 10.by { .is_pell_pseudoprime && .is_composite }  # OEIS: A099011

Aliases: is_pell_pseudoprime

is_perrin_psp

    n.is_perrin_psp

Returns true if n passes the Perrin primality test.

Aliases: is_perrin_pseudoprime

is_plumb_psp

    n.is_plumb_psp

Return true if n passes Colin Plumb's Euler Criterion primality test.

Aliases: is_euler_plumb_psp, is_plumb_pseudoprime, is_euler_plumb_pseudoprime

is_polygonal

    is_polygonal(n,k)

Returns true if n is a first k-gonal number.

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

is_polygonal2

    is_polygonal2(n,k)

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

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

is_pos

    x.is_pos

Returns true when x is a positive integer.

Aliases: is_positive

is_powerfree

    n.is_powerfree(k=2)

Returns true when all the exponents in the prime-power factorization of n are < k.

is_powerful

    n.is_powerful(k=2)

Returns true when all the exponents in the prime-power factorization of n are >= k.

is_power_of

    n.is_power_of(b)

Return true if n is a power of b, such that n = b^k for some k >= 0:

    n.is_power_of(b)    # true if n == b^k for some k >= 0

Example:

    say 1000.range.grep { .is_power_of(2) }     # powers of 2
    say 1000.range.grep { .is_power_of(5) }     # powers of 5

is_pow

    n.is_power
    n.is_power(k)

When k is omitted, it true if n is a perfect power.

When k is given, it returns true if n can be expressed as n = b^k for some b >= 1.

    say 225.is_power          # true: 225 == 15**2
    say 100.is_power(2)       # true: 100 is square (10**2)
    say 125.is_power(3)       # true: 125 is a cube ( 5**3)

Aliases: is_power, is_perfect_power

is_practical

    n.is_practical()

Returns true if n is a practical number (OEIS: A005153).

    say 20.by { .is_practical }

is_prime

    n.is_prime

Returns true if n is a prime number.

is_prime_power

    n.is_prime_power

Returns true if n is a power of some prime.

is_primitive_root

    n.is_primitive_root(m)

Returns true if n is a primitive root modulo m.

is_prob_prime

    is_prob_prime(n)

Returns true if n is probably prime. The method does some trial division, then it performs a B-PSW test.

is_prob_squarefree

    n.is_prob_squarefree(k)

Returns true iff n is not a power and is not divisible by a square <= k.

is_prov_prime

    is_prov_prime(n)

Returns true if n is provable prime.

Aliases: is_provable_prime

is_psp

    n.is_psp(bases...)

Returns true if n is a Fermat pseudoprime to the provided bases.

Aliases: is_fermat_psp, is_pseudoprime, is_fermat_pseudoprime

isqrt

    n.isqrt

Integer square root of n.

isqrtrem

    n.isqrtrem

Returns a list with the integer square root of n and the square root remainder of n.

Equivalent with:

    (n.isqrt, n - n.isqrt**2)

is_rat

    x.is_rat

Returns true if x is a rational number.

is_real

    x.is_real

Returns true if x is a real number.

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

is_rough

    n.is_rough(k)

Returns true if all prime factors of n are >= k.

    say 30.by { .is_rough(3) }  #=> OEIS: A005408
    say 30.by { .is_rough(5) }  #=> OEIS: A007310
    say 30.by { .is_rough(7) }  #=> OEIS: A007775
    # ...
    say 30.by { .is_rough(23) } #=> OEIS: A166063

is_safe_prime

    n.is_safe_prime

It returns true if both n and (n-1)/2 are prime.

    say 30.by { .is_safe_prime }    #=> OEIS: A005385

is_semiprime

    n.is_semiprime

Returns true if n has exactly two prime factors (not necessarily distinct).

is_smooth

    n.is_smooth(k)

Returns true if all the prime factors of n are <= k. False otherwise.

is_smooth_over_prod

    n.is_smooth_over_prod(k)

Returns true when n is smooth over the prime factors of k.

is_sqr

    n.is_sqr
    is_square(n)

Returns true if n is a perfect square integer.

Aliases: is_square, is_perfect_square

is_square_free

    n.is_square_free

Returns true if the prime factorization of n does not include duplicated factors (i.e.: n is not divisible by a square).

Aliases: is_squarefree

is_stronger_lucas_psp

    n.is_stronger_lucas_psp

Return true if n is an extra-strong Lucas pseudoprime.

Aliases: is_extra_strong_lucas_psp, is_stronger_lucas_pseudoprime, is_extra_strong_lucas_pseudoprime

is_strong_fib

    n.is_strong_fib

Teturns true if n is a strong Fibonacci pseudoprime, satisfying:

    V_n(P,Q) = P (mod)

for Q = -1 and all P.

Odd composite integer n is a strong Fibonacci pseudoprime iff:

    1) n is a Carmichael number: p-1 | n-1
    2) 2(p + 1) | (n − 1) or 2(p + 1) | (n − p)

for each prime p|n.

Example:

    say is_strong_fibonacci_pseudoprime(443372888629441)    #=> true
    say is_strong_fibonacci_pseudoprime(39671149333495681)  #=> true

Aliases: is_strong_fib_psp, is_strong_fibonacci, is_strong_fibonacci_psp, is_strong_fibonacci_pseudoprime

is_strongish_lucas_psp

    n.is_strongish_lucas_psp

Return true if n is almost an extra-strong Lucas pseudoprime.

Aliases: is_strongish_lucas_pseudoprime

is_strong_lucas_psp

    n.is_strong_lucas_psp

Return true if n is a strong Lucas pseudoprime.

Aliases: is_strong_lucas_pseudoprime

is_strong_psp

    n.is_strong_psp(bases...)

Return true if n is a strong pseudoprime.

Aliases: miller_rabin, is_strong_fermat_psp, is_strong_pseudoprime, is_strong_fermat_pseudoprime

is_super_psp

    n.is_super_psp(bases...)

It returns true if the given value of n is a super-pseudoprime to the given bases. When no base is given, the base 2 is used (which represents the Super-Poulet numbers: A050217)

    # Super-Poulet numbers (OEIS: A050217)
    say 1e4.range.grep { .is_super_pseudoprime }.grep{ .is_composite }

    # Super-Poulet numbers to base 3 (OEIS: A328662)
    say 1e4.range.grep { .is_super_pseudoprime(3) }.grep{ .is_composite }

    # Super-Poulet numbers to base 2 and 3
    say 1e5.range.grep { .is_super_pseudoprime(2, 3) }.grep{ .is_composite }

Aliases: is_super_pseudoprime, is_superpseudoprime

is_totient

    n.is_totient

Given an integer n, returns true if there exists an integer x such that euler_phi(x) == n.

isub

    isub(a,b)

Integer subtraction: a-b.

is_underwood_psp

    n.is_underwood_psp

Return true if n passes the efficient Frobenius test of Paul Underwood.

Aliases: is_underwood_pseudoprime, is_frobenius_underwood_psp, is_frobenius_underwood_pseudoprime

is_zero

    x.is_zero

Returns true when x equals 0.

jacobi

    jacobi(a,n)

Returns the Jacobi symbol: (a|n).

jordan_totient

    jordan_totient(n,k)

Jordan's totient J_k(n), which is a generalization of Euler's totient function.

kronecker

    kronecker(a,n)

Returns the Kronecker symbol: (a|n).

laguerre

    laguerre(n)
    laguerre(n, x)

Laguerre polynomials: L_n(x).

When x is omitted, a Polynomial object is returned.

Aliases: laguerreL, laguerre_polynomial

lambda

    lambda(n)

Carmichael lambda function: λ(n), defined as the smallest positive integer m such that:

    powmod(a, m, n) == 1

for every integer a between 1 and n that is coprime to n.

Alias: carmichael_lambda.

lambert_w

    lambert_w(x)

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)

lcm

    lcm(...)

Least common multiple of a list of integers.

legendre

    legendre(a,p)

Returns the Legendre symbol: (a|p).

legendreP

    legendreP(n)
    legendreP(n,x)

Legendre polynomials: P_n(x).

When x is omitted, a Polynomial object is returned.

Aliases: legendrep, legendre_polynomial

legendre_phi

    n.legendre_phi(k)

Returns the count of numbers <= n that are not divisible by the first k primes.

Equivalent with:

    prime(k+1).rough_count(n)

len

    n.len(b=10)

Returns the number of digits of the integer part of n in a given base..

    say 5040.len        #=> 4
    say 5040.len(2)     #=> 13

Aliases: size, length

lgamma

    lgamma(x)

Natural logarithm of abs(Γ(x)).

Aliases: gamma_abs_log

lgrt

    lgrt(x)

Returns the "logarithm-root" of x, such that lgrt(x) ** lgrt(x) =~= x.

    say lgrt(100)       #=> 3.59728502354041750549765225178229
    say lgrt(-100)      #=> 3.70202936660214594290193962952737+1.34823128471151901327831464969872i

li

    li(x)

Returns the logarithmic integral of x.

    say 100.li  # prints: 30.12614158...

li2

    li2(x)

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

liouville

    liouville(n)

The Liouville function.

Equivalent to:

    (-1)**omega(n)

liouville_sum

    liouville_sum(n)
    liouville_sum(a,b)

Computes partial sums of the Liouville lambda function:

    Sum_{k=1..n} liouville(k)

When an additional argument is given, the returned result is:

    Sum_{k=a..b} liouville(k)

Example:

    say liouville_sum(10**9)           #=> -25216
    say liouville_sum(10**9, 10**10)   #=> -90809

ln

    x.ln

Natural logarithm of x.

ln2

    Num.ln2

Returns the natural logarithm of 2 constant.

lnbern

    lnbern(n)

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

Aliases: bern_log, lnbernreal, bernoulli_log

lngamma

    lngamma(x)

Natural logarithm of Γ(x).

Aliases: gamma_log

lnsuperfactorial

    lnsuperfactorial(n)

Natural logarithm of superfactorial(n).

Aliases: superfactorial_ln, superfactorial_log

lnsuperprimorial

    lnsuperprimorial(n)

Natural logarithm of superprimorial(n).

Aliases: superprimorial_ln, superprimorial_log

log

    log(x)
    log(x, b)

Natural logarithm of x to base e, or to a given base b.

log10

    x.log10

Logarithm of x to base 10.

log2

    x.log2

Logarithm of x to base 2.

logarithmic_derivative

    logarithmic_derivative(n)

Return the logarithmic derivative of n, defined as:

    derivative(n)/n

lpf

    lpf(n)

Returns the least prime factor of n.

Defined with the base-cases:

    lpf(0) = 0
    lpf(1) = 1

Example:

    say lpf(fibonacci(1234))    #=> 234461

lsb

    lsb(n)

Returns the least significant bit of n.

    say 0b110010101111000000.lsb    # 6

lucas

    lucas(n)

Returns the n-th Lucas number.

lucas_factor

    n.lucas_factor(j=1, tries=100)

Effective in factoring Carmichael numbers, Fermat pseudoprimes, Lucas pseudoprimes and Lucas-Carmichael numbers.

    say lucas_factor(2425361208749736840354501506901183117777758034612345610725789878400467)

The product of the factors, will give back n. However, some factors may be composite.

Aliases: lucas_miller_factor

lucas_mod

    lucasmod(n,m)

Efficiently compute the n-th Lucas number modulo m.

Aliases: lucasmod

lucasU

    lucasU(P, Q, n)

The Lucas U_n(P, Q) function.

    say 20.of{|n| lucasU(1, -1, n) }    # the Fibonacci numbers
    say 20.of{|n| lucasU(2, -1, n) }    # the Pell numbers
    say 20.of{|n| lucasU(1, -2, n) }    # the Jacobsthal numbers

Aliases: lucasu

lucasUmod

    lucasUmod(P,Q,n,m)

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

Aliases: lucasumod

lucasUVmod

    lucasUVmod(P,Q,n,m)

Efficiently compute the Lucas U_n(P, Q) and V_n(P,Q) functions modulo m.

Equivalent with:

    (lucasUmod(P,Q,n,m), lucasVmod(P,Q,n,m))

Aliases: lucasuvmod

lucasV

    lucasV(P, Q, n)

The Lucas V_n(P, Q) function.

    say 20.of{|n| lucasV(1, -1, n) }    # the Lucas numbers
    say 20.of{|n| lucasV(2, -1, n) }    # the Pell-Lucas numbers
    say 20.of{|n| lucasV(1, -2, n) }    # the Jacobsthal-Lucas numbers

Aliases: lucasv

lucasvmod

    lucasVmod(P,Q,n,m)

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

Aliases: lucasVmod

make_coprime

    n.make_coprime(k)

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

mangoldt

    mangoldt(n)

The Mangoldt function. For the exponential values, see exp_mangoldt.

max

    max(...)

Returns the maximum value from a list of numbers.

mbe_factor

    n.mbe_factor(tries=10)

Tries to find a factor of n, by using the "Modular Binary Exponentiation" factorization method (randomized version).

This method is particularly effective for numbers that contain a prime factor p such that p-1 is sufficiently smooth.

The running time of the method, is: O(tries * log(n)^2).

Example:

    say mbe_factor(2**64 + 1, 1)   #=> [274177, 67280421310721]

The product of the factors, will give back n. However, some factors may be composite.

mertens

    mertens(n)
    mertens(a,b)

Returns the Mertens functions, which is defined as the partial sums of the Moebius function:

    Sum_{k=1..n} moebius(k)

When an additional argument is given, the returned result is:

    Sum_{k=a..b} moebius(k)

Example:

    say mertens(100000)     # equivalent with: (1..100000 -> sum { .moebius })
    say mertens(21, 123)    # equivalent with: (21..123 -> sum { .moebius })

mfac

    mfac(n,k)
    mfactorial(n,k)

The generalized multi-factorial of n.

    say 15.of { .mfac(2) }    # double-factorials (OEIS: A006882)
    say 15.of { .mfac(3) }    # triple-factorials (OEIS: A007661)

Aliases: mfactorial, multi_factorial

miller_factor

    n.miller_factor(tries=100)

Effective in factoring Carmichael numbers and Fermat pseudoprimes.

It returns an array with the factors of n. However, sometimes, not all factors are prime.

    say miller_factor(58571442634534443082821160508299574798027946748324125518533225605795841)

The product of the factors, will give back n. However, some factors may be composite.

Aliases: miller_rabin_factor

miller_rabin_random

    n.miller_rabin_random(k)

Return true if n passes the Miller-Rabin primality test with k random bases.

min

    min(...)

Returns the smallest value from a list of numbers.

modular_quadratic_formula

    modular_quadratic_formula(a,b,c,m)

Returns an array with all the positive solutions for x to the following modular quadratic equation:

    a*x^2 + b*x + c == 0 (mod m)

where a,b,c are rational values and m is a positive integer.

Example:

    say modular_quadratic_formula(3,4,5,124)  #=> [47, 55, 109, 117]

mone

    Num.mone

Returns the -1 value.

motzkin

    motzkin(n)

Returns the n-th Motzkin number. (OEIS: A001006)

    say 10.of { .motzkin }   #=> [1, 1, 2, 4, 9, 21, 51, 127, 323, 835]

msb

    msb(n)

Returns the most significant bit of n.

    say 0b110010101111000000.msb    # 17

mulmod

    mulmod(a,b,m)

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

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

multinomial

    multinomial(...)

The multinomial coefficient, given a list of native integers.

    say multinomial(1, 4, 4, 2)     #=> 34650

nan

    Num.nan

Returns the Not-a-Number special value (NaN).

nbsigma

    nbsigma(n, k=1)

Returns the sum of the non-bi-unitary divisors of n, each divisor raised to the k-th power.

    say 30.of { .nbsigma }      #=> OEIS: A319072

nbsigma0

    nbsigma0(n)

Returns the count of the non-bi-unitary divisors of n.

n_composites

    n_composites(n, start=4)

Returns n consecutive composite numbers starting from start.

    say n_composites(10)        #=> [4, 6, 8, 9, 10, 12, 14, 15, 16, 18]
    say n_composites(5, 50)     #=> [50, 51, 52, 54, 55]

Aliases: ncomposites, next_composites

nd

    n.st({...})
    n.nd({...})
    n.rd({...})
    n.th({...})

It returns the n-th value for which the provided block evaluates to a true value, starting counting from 0.

    say 100.th { .is_prime }    # 100-th prime

Also aliased as .st, .nd and .rd:

    say 1.st { .is_prime }      # first prime
    say 2.nd { .is_prime }      # second prime
    say 3.rd { .is_prime }      # third prime

Aliases: rd, st, th

neg

    x.neg

Negates the sign of <Cx> (equivalent with: -x).

nesigma

    nesigma(n, k=1)

Returns the sum of the non-exponential divisors of n, each divisor raised to the k-th power.

    say 30.of { .nesigma }      #=> OEIS: A160135

nesigma0

    nesigma0(n)

Returns the count of the non-exponential divisors of n.

    say 30.of { .nesigma0 }     #=> OEIS: A160097

new

    Number(string, base=10)
    Num.new(string, base=10)

Create a new Number object, given a string and a base.

Aliases: call

next_composite

    n.next_composite

Given a non-negative integer n, it returns the next composite number after n.

next_palindrome

    n.next_palindrome(b=10)

Efficiently returns the next palindrome in base-b greater than n.

    # Iterate over the base-10 palindromic numbers < 10^6
    for (var n = 0; n < 1e6; n = n.next_palindrome) {
        say n
    }

next_pow

    n.next_pow(b)

Returns the next perfect power greater than n, with base b.

    say 63.next_pow(2)      #=> 64
    say 64.next_pow(2)      #=> 128

Equivalent with:

    b**(1+ilog(n,b))

Aliases: next_power

next_prime

    n.next_prime

Returns the next prime larger than n.

next_squarefree

    n.next_squarefree

Returns the next squarefree integer larger than n.

next_twin_prime

    n.next_twin_prime

Returns next twin prime number larger than n.

Provided by Math::Prime::Util::GMP >= 0.52.

ninf

    Num.ninf

Returns the negative infinity special value (-Inf).

nisigma

    nisigma(n, k=1)

Returns the sum of the non-infinitary divisors of n, each divisor raised to the k-th power.

    say 30.of { .nisigma }      #=> OEIS: A348271

nisigma0

    nisigma0(n)

Returns the count of the non-infinitary divisors of n.

    say 30.of { .nisigma0 }     #=> OEIS: A348341

nok

    nok(n,k)
    binomial(n,k)

Returns the binomial coefficient n over k, also called the "choose" function.

Equivalent to:

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

Aliases: binomial

norm

    norm(x)

Returns the normalized value of x: abs(x)^2.

n_primes

    n_primes(n, start=2)

Returns an array containing n consecutive primes that are `>= start` (if omitted, then start = 2).

    say n_primes(10)        #=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
    say n_primes(10, 1000)  #=> [1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061]

The value for start can be any arbitrarily large integer:

    say n_primes(10, 2**128 + 1)    # first 10 primes > 2^128

Aliases: nprimes, next_primes

nu

    r.nu
    r.numerator

Returns the numerator of rational number r.

    say numerator(43/97)     #=> 43

Aliases: numerator

nude

    nude(r)

Returns a list with the numerator and the denominator of a rational number r.

    say [nude(43/97)]       #=> [43, 97]

num2perm

    num2perm(n,k)

Given a non-negative integer n and integer k, return the rank k lexicographic permutation of n elements.

k will be interpreted as mod n!.

The inverse value for k is given by Array#perm2num:

    say num2perm(5, 43)             #=> [1, 4, 0, 3, 2]
    say num2perm(5, 43).perm2num    #=> 43

numify

    n.numify

Returns a raw native number representation for the self-number.

Can be used for assigning values to Num!PREC variable.

    local Num!PREC = 42.numify  # set precision to 42 bits
    say sqrt(2)                 # 1.414213562

Native numbers can also be used when indexing an array:

    var arr = [42, 43, 44]
    var idx = 2.numify
    say arr[idx]            #=> 44

Although this may or may not be actually faster.

nusigma

    nusigma(n, k=1)

Returns the sum of the non-unitary divisors of n, each divisor raised to the k-th power.

    say 30.of { .nusigma }     #=> OEIS: A048146

nusigma0

    nusigma0(n)

Returns the count of the non-unitary divisors of n.

    say 30.of { .nusigma0 }    #=> OEIS: A048105

of

    n.of {|k| ... }

Returns an array with n elements mapped to the given block. The block is called with k = 0,1,2...,n-1.

    say 10.of { _*_ }       #=> first 10 squares
    say 10.of { .fib }      #=> first 10 Fibonacci numbers

omega_prime_divisors

    n.omega_prime_divisors
    n.omega_prime_divisors(k)

Returns the k-omega prime divisors of n.

    say 5040.omega_prime_divisors(4)    #=> [210, 420, 630, 840, 1260, 1680, 2520, 5040]

When k is omitted, an array of arrays with the k-omega prime divisors of n, for each k in the range 0..omega(n), is returned:

    say 120.omega_prime_divisors        #=> [[1], [2, 3, 4, 5, 8], [6, 10, 12, 15, 20, 24, 40], [30, 60, 120]]

omega_prime_count

    k.omega_prime_count(n)
    k.omega_prime_count(a,b)

Returns the number of k-omega primes <= n, or in the range a..b.

    say 1.omega_prime_count(100)            # number prime powers <= 100
    say 2.omega_prime_count(50, 100)        # number of 2-omega primes in range 50..100

Aliases: omega_primepi

omega_primes

    k.omega_primes(n)
    k.omega_primes(a,b)

Returns an array with k-omega primes <= n, or in the range a..b.

k-omega primes are numbers n such that omega(n) == k.

    say 1.omega_primes(100)         # prime powers <= 100
    say 2.omega_primes(50, 100)     # 2-omega primes in range 50..100

one

    Num.one

Returns the 1 value.

partitions

    partitions(n)

Returns the number of partitions of n.

Aliases: partition_number

parts

    x.parts

Returns an array with the real and imaginary parts of x.

    say parts(5)        #=> [5, 0]
    say parts(3+4i)     #=> [3, 4]

pbrent_factor

    n.pbrent_factor
    n.pbrent_factor(tries)

Pollard-Brent rho factorization method.

The product of the factors, will give back n. However, some factors may be composite.

perfect_power

    n.perfect_power

Returns the largest power k of n for which there exists an integer r, such that: n = r^k.

    say perfect_power(15**5)    #=> 5

perfect_root

    n.perfect_root

Returns the smallest root r of n for which there exists an integer k, such that: n = r^k.

    say perfect_root(15**5)    #=> 15

permutations

    n.permutations

Returns an array of arrays with the permutations of the integers in the range 0..n-1, or iterates over the permutations when a block is given.

    5.permutations {|*a| say a }

pi_k

    k.almost_prime_count(n)
    k.almost_prime_count(a,b)

Returns the number of k-almost primes <= n, or in the range a..b.

    say 1.almost_prime_count(100)           # count of primes <= 100
    say 2.almost_prime_count(50, 100)       # count of semiprimes in range 50..100

Aliases: almost_primepi, almost_prime_count

pm1_factor

    n.pm1_factor
    n.pm1_factor(B)

Pollard p-1 factorization method.

The product of the factors, will give back n. However, some factors may be composite.

Aliases: pminus1_factor

pn_primes

    pn_primes(n)
    pn_primes(a,b)

Returns the first n prime numbers, or the primes in the range prime(a)..prime(b).

    say pn_primes(25)        # the first 25 primes
    say pn_primes(100, 110)  # the primes from 100-th prime to 110-th prime (inclusive)

pn_primorial

    pn_primorial(n)

Returns the product of the first n primes.

polygonal

    polygonal(n,k)

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

   say 10.of {|n| polygonal( n, 3) }  # triangular numbers
   say 10.of {|n| polygonal( n, 5) }  # pentagonal numbers
   say 10.of {|n| polygonal(-n, 5) }  # second pentagonal numbers

polygonal_root

    polygonal_root(n,k)

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

    say polygonal_root(n, 3)      # triangular root
    say polygonal_root(n, 5)      # pentagonal root

polygonal_root2

    polygonal_root2(n,k)

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

    say polygonal_root2(n, 5)      # second pentagonal root

polymod

    n.polymod(...)

Returns a list of mod results corresponding to the divisors in given list.

    say [120.polymod(10)]    # (0, 12)
    say [120.polymod(10,10)] # [0, 2, 1]

Particularly useful for:

    var (sec, min, hours, days) = seconds.polymod(60, 60, 24)

popcount

    n.popcount

Number of 1's in binary representation of n.

This value is also known as the Hamming weight value.

Aliases: hammingweight

power_count

    n.power_count

Returns the number of perfect powers <= n.

    say power_count(10**6)      #=> 1111
    say power_count(10**20)     #=> 10004650118

Aliases: perfect_power_count

power_divisors

    k.power_divisors(n)

Return an array with the k-th power divisors of n.

    say 3.power_divisors(10!)       #=> [1, 8, 27, 64, 216, 1728]
    say 4.power_divisors(10!)       #=> [1, 16, 81, 256, 1296, 20736]

Equivalent with:

    n.divisors.grep { .is_power(k) }

powerfree_count

    k.powerfree_count(n)
    k.powerfree_count(a,b)

It efficiently counts the number of k-powerfree numbers <= n, or in the range a..b:

    say 3.powerfree_count(100)       #=> count of cubefree numbers <= 100
    say 3.powerfree_count(50, 100)   #=> count of cubefree numbers in the range 50..100

powerfree_divisors

    k.powerfree_divisors(n)

Returns an array with the k-powerfree divisors of n.

    say 2.powerfree_divisors(5040)      # squarefree divisors of 5040
    say 3.powerfree_divisors(5040)      # cubefree divisors of 5040

powerfree_part

    k.powerfree_part(n)

Returns the k-powerfree part of n.

    say 30.of { 2.powerfree_part(_) }       # squarefree part (OEIS: A007913)
    say 30.of { 3.powerfree_part(_) }       # cubefree part (OEIS: A050985)

powerfree_part_sum

    k.powerfree_part_sum(n)
    k.powerfree_part_sum(a,b)

Returns the sum of the k-powerfree parts of integers <= n or in the range a..b:

    say 2.powerfree_part_sum(100)            # sum of squarefree part of n for n <= 100
    say 3.powerfree_part_sum(50, 100)        # sum of cubefree part of n for n in the range 50..100

powerfree_sigma

    k.powerfree_sigma(n, j=1)

Returns the sum of the k-powerfree divisors of n, each divisor raised to the power j.

    say 30.of { 2.powerfree_sigma(_) }        # OEIS: A048250
    say 30.of { 3.powerfree_sigma(_) }        # OEIS: A073185

Equivalent with (but much faster):

    n.divisors.grep { .is_powerfree(k) }.sum {|d| d**j }

powerfree_sigma0

    k.powerfree_sigma0(n)

Returns the number of the k-powerfree divisors of n.

    say 30.of { 3.powerfree_sigma0(_) }       # OEIS: A073184

powerfree_sum

    k.powerfree_sum(n)
    k.powerfree_sum(a,b)

Returns the sum of k-powerfree numbers <= n or in the range a..b:

    say 2.powerfree_sum(100)            # sum of squarefree numbers <= 100
    say 3.powerfree_sum(50, 100)        # sum of cubefree numbers in the range 50..100

powerfree_udivisors

    k.powerfree_udivisors(n)

Returns an array with the k-powerfree unitary divisors of n.

    say 2.powerfree_udivisors(5040)      # squarefree unitary divisors of 5040
    say 3.powerfree_udivisors(5040)      # cubefree unitary divisors of 5040

Equivalent with (but much faster):

    n.udivisors.grep { .is_powerfree(k) }
    k.powerfree_divisors(n).grep {|d| gcd(n/d, d) == 1 }

Aliases: powerfree_unitary_divisors, unitary_powerfree_divisors

powerfree_usigma

    k.powerfree_usigma(n, j=1)

Returns the sum of the k-powerfree unitary divisors of n, each divisor raised to the power j.

    say 20.of { 2.powerfree_usigma(_) }        # OEIS: A092261
    say 20.of { 2.powerfree_usigma(_, 2) }     # OEIS: A091306

Equivalent with (but much faster):

    n.udivisors.grep { .is_powerfree(k) }.sum {|d| d**j }

powerfree_usigma0

    k.powerfree_usigma0(n)

Returns the number of the k-powerfree unitary divisors of n.

    say 20.of { 2.powerfree_usigma0(_) }       # OEIS: A056671

powerful

    k.powerful(n)
    k.powerful(a,b)

It efficiently generates all the k-powerful numbers <= n, or in the range a..b.

    say 2.powerful(100)          #=> 2-powerful numbers <= 100
    say 2.powerful(50, 100)      #=> 2-powerful numbers in the range 50..100

powerful_count

    k.powerful_count(n)
    k.powerful_count(a,b)

It efficiently counts the number of k-powerful numbers <= n, or in the range a..b;

    say 2.powerful_count(100)       #=> count of 2-powerful numbers <= 100
    say 2.powerful_count(50, 100)   #=> count of 2-powerful numbers in the range 50..100

power_sigma

    k.power_sigma(n, j=1)

Returns the sum of the k-th power divisors of n, each divisor raised to the power j.

    say 30.of { 2.power_sigma(_) }        # OEIS: A035316
    say 30.of { 3.power_sigma(_) }        # OEIS: A113061

Equivalent with (but much faster):

    n.divisors.grep { .is_power(k) }.sum {|d| d**j }

power_sigma0

    k.power_sigma0(n)

Returns the number of the k-th power divisors of n.

    say 30.of { 2.power_sigma0(_) }       # OEIS: A046951

power_udivisors

    k.power_udivisors(n)

Returns an array with the k-th power unitary divisors of n.

    say 2.power_udivisors(15!)      #=> [1, 49, 729, 35721]
    say 3.power_udivisors(15!)      #=> [1, 125, 729, 91125]

Equivalent with:

    n.udivisors.grep { .is_power(k) }

Aliases: power_unitary_divisors, unitary_power_divisors

power_usigma

    k.power_usigma(n, j=1)

Returns the sum of the k-th power unitary divisors of n, each divisor raised to the power j.

Equivalent with (but much faster):

    n.udivisors.grep { .is_power(k) }.sum {|d| d**j }

power_usigma0

    k.power_usigma0(n)

Returns the number of the k-th power unitary divisors of n.

    say 30.of { 2.power_usigma0(_) }       # OEIS: A056624

pp1_factor

    n.pp1_factor(B)

Williams' p+1 factorization method.

The product of the factors, will give back n. However, some factors may be composite.

Aliases: pplus1_factor

pp_divisors

    pp_divisors(n)

Returns an array with the perfect power divisors of n.

    say 5040.pp_divisors        #=> [1, 4, 8, 9, 16, 36, 144]

Equivalent with:

    n.divisors.grep { .is_perfect_power }

Aliases: perfect_power_divisors

pp_udivisors

    pp_udivisors(n)

Returns an array with the perfect power unitary divisors of n, such that each divisor d is a perfect power and gcd(n/d, d) = 1.

    say 15!.pp_udivisors        #=> [1, 49, 125, 729, 2048, 35721, 91125]

Equivalent with:

    n.udivisors.grep { .is_perfect_power }

Aliases: perfect_power_udivisors, perfect_power_unitary_divisors

prev_pow

    n.prev_pow(b)

Returns the previous perfect power smaller than n, with base b. Returns NaN when n is <= 1.

    say 65.prev_pow(2)      #=> 64
    say 64.prev_pow(2)      #=> 32

Aliases: prev_power

prev_prime

    n.prev_prime

Returns the previous prime smaller than n.

prho_factor

    n.prho_factor
    n.prho_factor(tries)

Pollard rho factorization method.

The product of the factors, will give back n. However, some factors may be composite.

primality_pretest

    n.primality_pretest()

The method returns true when n passes the internal primality pretest (when n is large enough and it has no small factors).

prime

    prime(n)

Returns the n-th prime number.

    say prime(100)      #  100th prime: 541
    say prime(1000)     # 1000th prime: 7919

Aliases: nth_prime

prime_divisors

    prime_divisors(n)

Returns the unique prime factors of n.

prime_lower

    n.prime_lower

Lower bound for the n-th prime.

Aliases: nth_prime_lower

primepi

    primepi(n)
    primepi(a,b)

Returns the number of primes <= n, or in the range a..b.

Aliases: prime_count, count_primes

primepi_lower

    n.primepi_lower

Lower bound for prime_count(n).

Aliases: prime_count_lower

primepi_upper

    n.primepi_upper

Upper bound for prime_count(n).

Aliases: prime_count_upper

prime_power

    n.prime_power

Returns the exponent k if n is a power of the form n = p^k for some prime p. Returns 1 otherwise.

    say prime_power(15)     #=> 1
    say prime_power(43**5)  #=> 5

prime_power_count

    prime_power_count(n)
    prime_power_count(a,b)

Returns the number of prime powers <= n, or in the range a..b.

    say prime_power_count(1e15)     # number of prime powers <= 10^15
    say prime_power_count(1e6, 1e8) # number of prime powers in [10^6, 10^8]

prime_power_divisors

    n.prime_power_divisors()

Returns the prime power divisors of n.

    say prime_power_divisors(5040)  #=> [2, 3, 4, 5, 7, 8, 9, 16]

Equivalent with:

    n.divisors.grep{.is_prime_power}

prime_power_sigma

    n.prime_power_sigma(k=1)

Sum of the prime power divisors of n, each divisor raised to the k-th power.

    say prime_power_sigma(10!)      #=> 667
    say prime_power_sigma(10!, 2)   #=> 95459

Equivalent with:

    n.prime_power_divisors.sum {|d| d**k }

prime_power_sigma0

    prime_power_sigma0(n)

Returns the number of prime power divisors of n.

Equivalent with:

    bigomega(n)

prime_power_udivisors

    prime_power_udivisors(n)

Returns the unitary prime power divisors of n.

    say prime_power_udivisors(10!)  #=> [7, 25, 81, 256]

The product of the unitary prime power divisors of a number, is the number itself.

This method is equivalent with:

    n.factor_map {|p,k| p**k }.sort

Aliases: prime_power_unitary_divisors, unitary_prime_power_divisors

prime_power_usigma

    Number.prime_power_usigma(k=1)

Returns the sum of the unitary prime power divisors of n, each divisor raised to power k.

    say prime_power_usigma(10!)     #=> 369     (== 7 + 25 + 81 + 256)
    say prime_power_usigma(10!, 2)  #=> 72771   (== 7^2 + 25^2 + 81^2 + 256^2)

Equivalent with:

    n.factor_map {|p,e| p**(e * k) }.sum

prime_power_usigma0

    prime_power_usigma0(n)

Returns the number of unitary prime power divisors of n.

Equivalent with:

    omega(n)

prime_root

    n.prime_root

Returns the prime p if n can be expressed as n = p^k for some prime number p and integer k. Returns n otherwise.

    say prime_root(15)      #=> 15
    say prime_root(43**5)   #=> 43

primes

    primes(n)
    primes(a,b)

Returns an array with the prime numbers <= n, or in the range a..b.

prime_sigma

    n.prime_sigma(k=1)

Sum of the unique prime divisors of n, each divisor raised to the k-th power.

    say prime_sigma(100!)       #=> 1060
    say prime_sigma(100!, 2)    #=> 65796

prime_sigma0

    prime_sigma0(n)

Returns the number of prime divisors of n.

Equivalent with:

    omega(n)

prime_sum

    prime_sum(n)
    prime_sum(a,b)

Sum of the prime numbers <= n, or in the range a..b.

Aliases: primes_sum, sum_primes

prime_udivisors

    n.prime_udivisors

Returns the unique unitary prime factors of n.

Aliases: prime_unitary_divisors, unitary_prime_divisors

prime_upper

    n.prime_upper

Upper bound for the n-th prime.

Aliases: nth_prime_upper

prime_usigma

    n.prime_usigma(k=1)

Sum of the unique unitary prime divisors of n, each divisor raised to the k-th power.

    say prime_usigma(100!)      #=> 732
    say prime_usigma(100!, 2)   #=> 55330

prime_usigma0

    prime_usigma0(n)

The number of unique unitary prime divisors of n.

primitive_part

    n.primitive_part(f)

Returns the primitive part of f(n), for n > 0, such that:

    a(n) = primitive part of f(n)
    f(n) = Product_{d|n} a(d)

Example:

    func f(n) { n.fib }
    func a(n) { n.primitive_part(f) }

    say 20.of { a(_) }
    say 20.of { f(_) }
    say 20.of { .divisors.prod {|d| a(d) } }

primorial

    Number.primorial()

Returns the

primorial_deflation

    n.primorial_deflation()

Primorial deflation of n, satisfying:

    primorial_inflation(primorial_deflation(n)) = n

Defined as:

    primorial_deflation(n) = A319626(n)/A319627(n)

primorial_inflation

    n.primorial_inflation()

Primorial inflation of n: fully multiplicative with a(p) = primorial(p).

Defined as:

    primorial_inflation(n) = A108951(n)

The method also accepts n to be a fraction, which is computed as:

    primorial_inflation(a/b) = primorial_inflation(a)/primorial_inflation(b)

psi

    n.psi(k=1)
    dedekind_psi(n,k=1)

Dedekind psi function.

    say 10.of { .dedekind_psi    }   #=> [0, 1, 3, 4, 6, 6, 12, 8, 12, 12]
    say 10.of { .dedekind_psi(2) }   #=> [0, 1, 5, 10, 20, 26, 50, 50, 80, 90]

Aliases: dedekind_psi

qnr

    qnr(n)

Returns the least quadratic non-residue of n.

    say qnr(17676352761153241)      #=> 37
    say qnr(172138573277896681)     #=> 41

Aliases: quadratic_nonresidue

qs_factor

    qs_factor(n)

Pomerance's Quadratic Sieve factorization method (SIMPQS).

The product of the factors, will give back n. However, some factors may be composite.

quadratic_formula

    quadratic_formula(a,b,c)

Returns a list of solutions (x_1, x_2) to the quadratic equation: a*x^2 + b*x + c = 0, defined as:

    (-b ± sqrt(b^2 - 4ac)) / (2a)

Example:

    say [quadratic_formula(13, -42, -34)]     #=> [3.9011...., -0.6704...]

quadratic_formulaQ

    quadratic_formulaQ(a,b,c)

Returns a list of Quadratic objects, which are solutions (x_1, x_2) to the quadratic equation: a*x^2 + b*x + c = 0.

    say [quadratic_formulaQ(3,4,5)]

Outputs:

    [Quadratic(-2/3, 1/6, -44), Quadratic(-2/3, -1/6, -44)]

rad

    rad(n)

Returns the radical of n, which is the largest squarefree divisor of n.

    say rad(2**5 * 3**9)    #=> 6

Equivalent to:

    n.factor.uniq.prod

rad2deg

    rad2deg(x)

Convert radians to degrees.

    say rad2deg(Num.pi)     #=> 180

ramanujan_sum

    ramanujan_sum(n,q)

The Ramanujan sum function, defined as:

    c_q(n) = μ(q/gcd(n,q)) * φ(q) / φ(q/gcd(n,q))

Example:

    say 20.of {|q| ramanujan_sum(2, q) }    #=> OEIS: A086831

ramanujan_tau

    ramanujan_tau(n)

Ramanujan's tau function.

rand

    rand(n)
    rand(a,b)

Returns a pseudorandom floating-point in the interval [0,n), or in the interval [a,b).

random_bytes

    n.random_bytes

Returns an array with n random values between 0 and 255.

random_maurer_nbit_prime

    random_maurer_nbit_prime(n)

Generate a random n-bit Marurer prime.

Aliases: random_nbit_maurer_prime

random_nbit_prime

    random_nbit_prime(n)

Returns a random n-bit prime.

    say random_nbit_prime(100)      # 100-bit random prime

random_nbit_strong_prime

    random_nbit_strong_prime(n)

Generate a random n-bit strong prime number.

Aliases: random_strong_nbit_prime

random_ndigit_prime

    random_ndigit_prime(n)

Returns a random n-digit prime.

    say random_ndigit_prime(100)    # 100-digit random prime

random_prime

    random_prime(n)
    random_prime(a,b)

Returns a random prime <= n, or in the range a..b.

    say random_prime(100)         # random prime in range [2, 100]
    say random_prime(100, 1000)   # random prime in range [100, 1000]

random_safe_prime

    random_safe_prime(n)

Returns a random n-bit safe-prime.

    say random_safe_prime(512)   #=> 512-bit safe prime

Provided by Math::Prime::Util::GMP >= 0.52.

random_string

    n.random_string

Returns a string with n random characters (bytes).

range

    range(n)
    range(a,b)
    range(a,b,step)

Creates a new RangeNumber object.

    say range(10)           #=> RangeNum(0, 9, 1)
    say range(1, 10)        #=> RangeNum(1, 10, 1)
    say range(1, 10, 2)     #=> RangeNum(1, 10, 2)

rat

    x.rat

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

Aliases: to_r, to_rat

rat_approx

    x.rat_approx

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

    say rat_approx(3.14).as_frac        #=> 22/7
    say rat_approx(zeta(-5)).as_frac    #=> -1/252

Returns NaN when x is not a real number.

re

    re(z)

Returns the real part of a complex number z.

Aliases: real

reals

    reals(z)

Returns a list with the real and imaginary parts of z.

remdiv

    n.remdiv(k)

Removes all occurrences of the divisor k from integer n.

Equivalent with:

    n / k**valuation(n,k)

Aliases: remove

rising_factorial

    rising_factorial(n,k)

Rising factorial: n^(k) = 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)

root

    root(n,k)

The k-th root of n, defined as:

    n**(1/k)

rotate

    rotate(n, k, b=10)

Rotate the digits of n to the left when k is positive or to the right otherwise, in a given base b, or base 10 when no base is given.

    say rotate(12345, 2)         #=> 34512
    say rotate(12345, -1)        #=> 51234

rough_count

    k.rough_count(n)
    k.rough_count(a,b)

Returns the number of k-rough numbers <= n, or in the range a..b.

    say 97.rough_count(1e6)    #=> 122005
    say 23.rough_count(1e9)    #=> 171024023

Also works with arbitrarily large n:

    say 43.rough_count(1e34)   #=> 1450936704022016442012254601096989

rough_part

    n.rough_part(k)

It returns the k-rough part of n that contains all the prime factors p|n such that p >= k.

    say 15.of {|n| rough_part(n!, 3) }      #=> OEIS: A049606

round

    round(x,k=0)

Rounds x to the k-th decimal place.

A negative argument rounds that many digits after the decimal point, while a positive argument rounds that many digits before the decimal point.

    say round(1234.567)             #=> 1235
    say round(1234.567, 2)          #=> 1200
    say round(3.123+4.567i, -2)     #=> 3.12+4.57*i

Aliases: roundf

run

    run(a,b)

Given two arguments, it returns the second one.

sec

    sec(x)

Trigonometric secant function.

secant_number

    secant_number(n)

Return the n-th secant/zig number. (OEIS: A000364)

sech

    sech(x)

Hyperbolic secant function.

seed

    seed(n)

Re-seed the rand() function. The value for n can be any arbitrary large integer.

semiprime

    semiprime(n)

Returns the n-th semiprime number.

    say 10.of {|k| semiprime(10**k) }    #=> OEIS: A114125

Aliases: nth_semiprime

semiprime_count

    semiprime_count(n)
    semiprime_count(a,b)

Counts the number of semiprimes <= n (OEIS: A072000), or in the range a..b.

    say 20.of {|k| semiprime_count(2**k) }

semiprimes

    semiprimes(n)
    semiprimes(a,b)

Returns an array with the semiprimes <= n, or in the range a..b.

    say semiprimes(100)             # semiprimes <= 100
    say semiprimes(50, 100)         # semiprimes in the range [50, 100]

setbit

    setbit(n,k)

Set the k-th bit of integer n to 1.

    say setbit(0b1000, 0).as_bin    #=> 1001
    say setbit(0b1000, 2).as_bin    #=> 1100

sgn

    sgn(x)

Returns the sign of x.

Defined as:

    x / abs(x)

Aliases: sign

sigma0

    tau(n)
    sigma0(n)

Returns the number of positive divisors of n.

sin

    sin(x)

Trigonometric sine function.

sin_cos

    sin_cos(x)

Returns a list with the values (sin(x), cos(x)).

sinh

    sinh(x)

Hyperbolic sine function.

smooth_count

    k.smooth_count(n)
    k.smooth_count(a,b)

Returns the number of k-smooth numbers <= n, or in the range a..b.

    say 30.of {|n| 13.smooth_count(10**n) }   #=> OEIS: A106629

smooth_numbers

    smooth_numbers(limit, [p1,p2,...])
    smooth_numbers(limit, [p1,p2,...], {|n,p| ... })

Returns an array containing all the smooth numbers that factorize over the given array of primes.

    say smooth_numbers(100, [2,3,5])    # 5-smooth numbers <= 100

An optional block can be provided, which is called with two arguments, n and p, where p is the current prime and n is a smooth number that is a multiple of p. If the block returns true, then the number n will be included in the returned array.

    # 5-smooth numbers <= 100 that are squarefree
    say smooth_numbers(100, [2,3,5], {|n,p| n.valuation(p) < 2 })

    # 5-smooth numbers <= 100 that are cubefree
    say smooth_numbers(100, [2,3,5], {|n,p| n.valuation(p) < 3 })

smooth_part

    n.smooth_part(k)

It efficiently returns the largest divisor of n that is k-smooth.

    say 20.of {|n| smooth_part(n!, 3) }     #=> OEIS: A118381

solve_lcg

    solve_lcg(n, r, m)

Return the smallest solution for x to the following linear congruence:

    n*x == r (mod m)

Example:

    say solve_lcg(143, 44, 231)     #=> 10

Return NaN when no solution exists (i.e.: when r is not divisible by gcd(n, m)).

Aliases: solve_linear_congruence

solve_pell

    solve_pell(d, k=1)

Find the smallest pair of integers (x,y) that satisfy the Pell equation: x^2 - d*y^2 = k.

    say [solve_pell(863)]       #=> [18524026608, 630565199]
    say [solve_pell(953, -1)]   #=> [2746864744, 88979677]

Return (nil,nil) when a solution does not exist.

sopf

    sopf(n)

Sum of the distinct primes dividing n.

    say 30.of { .sopf }     #=> OEIS: A008472

sopfr

    sopfr(n)

Sum of primes dividing n (with repetition).

    say 30.of { .sopfr }    #=> OEIS: A001414

sqr

    sqr(x)

Returns the square of x. Equivalent with x*x.

Aliases: square

sqrt

    sqrt(x)

Returns the square root of x. Equivalent with x**(1/2).

sqrt_cfrac

    n.sqrt_cfrac
    n.sqrt_cfrac(k)

Returns the expansion of the continued fraction for square root of n.

When an additional argument k is specified, it includes only the first k terms from the expansion period.

    say 28.sqrt_cfrac               #=> [5, 3, 2, 3, 10]
    say 28.sqrt_cfrac(2)            #=> [5, 3, 2]
    say 12345678910.sqrt_cfrac(10)  #=> [111111, 9, 26, 1, 2, 3, 1, 1, 2, 8, 1]

sqrt_cfrac_period

    n.sqrt_cfrac_period

Returns the period of the expansion of the continued fraction for square root of n.

    say 28.sqrt_cfrac_period        #=> [3, 2, 3, 10]

sqrt_cfrac_period_each

    n.sqrt_cfrac_period_each { ... }
    n.sqrt_cfrac_period_each({ ... }, max_iter)

Iterate over the period of the expansion of the continued fraction for square root of n.

    28.sqrt_cfrac_period_each {|r| say r }

sqrt_cfrac_period_len

    n.sqrt_cfrac_period_len

Returns the length of the period of continued fraction for square root of n. (OEIS: A003285)

sqrtmod

    sqrtmod(a,m)

Modular square root of a, returning a solution r, such that r^2 = a (mod m).

    say sqrtmod(544, 800)         #=> 512
    say sqrtmod(436, 1752)        #=> 1010

sqrtmod_all

    sqrtmod_all(a, n)

Given two integers a and n, return a sorted array of all modular square roots of a mod |n|. If no square root exists, an empty array is returned.

    say sqrtmod_all(4095, 8469)     #=> [1110, 1713, 3933, 4536, 6756, 7359]

sqrtQ

    sqrtQ(n)

Returns a Quadratic object, representing sqrt(n).

square_divisors

    square_divisors(n)

Returns the square divisors of n.

    say 5040.square_divisors    #=> [1, 4, 9, 16, 36, 144]

Equivalent with:

    n.divisors.grep { .is_square }

squarefree

    squarefree(n)
    squarefree(a,b)

Returns an array with the squarefree numbers <= n, or in the range a..b.

    # Squarefree numbers in the interval [100, 200]
    say squarefree(100, 200)

    # Squarefree numbers <= 100
    say squarefree(100)

squarefree_almost_primes

    k.squarefree_almost_primes(n)
    k.squarefree_almost_primes(a,b)

Returns an array with the squarefree k-almost primes <= n, or in the range a..b.

    say 2.squarefree_almost_primes(100)      #=> squarefree semiprimes <= 100
    say 2.squarefree_almost_primes(50, 100)  #=> squarefree semiprimes in the range 50..100

    say 3.squarefree_almost_primes(100)      #=> squarefree 3-almost primes <= 100
    say 3.squarefree_almost_primes(50, 100)  #=> squarefree 3-almost primes in the range 50..100

square_free_count

    square_free_count(n)
    square_free_count(a,b)

Returns the number of squarefree integers <= n, or in the range a..b.

    # The number of square-free integers between 10^5 and 10^6
    say square_free_count(10**5, 10**6) # 547132

    # The number of square-free integers <= 2^40
    say square_free_count(2**40)        # 668422917419

Aliases: squarefree_count

squarefree_divisors

    squarefree_divisors(n)

Returns an array with the square-free divisors of n.

    say squarefree_divisors(120)  #=> [1, 2, 3, 5, 6, 10, 15, 30]

squarefree_pi_k

    k.squarefree_almost_prime_count(n)
    k.squarefree_almost_prime_count(a,b)

Returns the number of squarefree k-almost primes <= n, or in the range a..b.

    say 1.squarefree_almost_prime_count(1000)          # count of primes <= 1000
    say 2.squarefree_almost_prime_count(50, 1000)      # count of squarefree semiprimes in range 50..1000

Aliases: squarefree_almost_primepi, squarefree_almost_prime_count

squarefree_sigma

    squarefree_sigma(n,k=1)

Sum of the square free divisors of n, each divisor raised to power k.

    say squarefree_sigma(5040)      #=> 576
    say squarefree_sigma(5040, 2)   #=> 65000

squarefree_sum

    squarefree_sum(n)
    squarefree_sum(a,b)

Returns the sum of squarefree numbers <= n or in the range a..b. (OEIS: A066779)

    say squarefree_sum(1e12)    #=> 303963551353876732927386
    say squarefree_sum(1e13)    #=> 30396355090144154315002969

squarefree_udivisors

    squarefree_udivisors(n)

Returns the unitary squarefree divisors of n.

    say squarefree_udivisors(5040)   #=> [1, 5, 7, 35]

Aliases: squarefree_unitary_divisors, unitary_squarefree_divisors

squarefree_usigma

    n.squarefree_usigma(k=1)

Sum of the unitary squarefree divisors of n, each divisor raised to the k-th power.

    say 5040.squarefree_usigma     #=> 48
    say 5040.squarefree_usigma(2)  #=> 1300

squarefree_usigma0

    squarefree_usigma0(n)

Returns the number of unitary squarefree divisors of n.

    say squarefree_usigma0(5040)    #=> 4

square_sigma

    n.square_sigma(k=1)

Sum of the square divisors of n, each divisor raised to the power k.

    say 5040.square_sigma       #=> 210
    say 5040.square_sigma(2)    #=> 22386

Equivalent with:

    n.square_divisors.sum {|d| d**k }

square_sigma0

    square_sigma0(n)

Returns the number of square divisors of n.

squares_r

    squares_r(n, k=2)

Sum of squares function r_k(n): returns the number of ways or representing n as a sum of k squares.

    say 30.of { .squares_r(2) }     # OEIS: A004018
    say 30.of { .squares_r(3) }     # OEIS: A005875
    say 30.of { .squares_r(4) }     # OEIS: A000118

Aliases: sum_of_squares_count

square_udivisors

    square_udivisors(n)

Returns the unitary square divisors of n, such that each divisor d is a square and gcd(n/d, d) = 1.

    say 5040.square_udivisors   #=> [1, 9, 16, 144]

Aliases: square_unitary_divisors, unitary_square_divisors

square_usigma

    n.square_usigma(k=1)

Sum of the unitary square divisors of n, each divisor raised to power k.

    say square_usigma(5040)     #=> 170
    say square_usigma(5040, 2)  #=> 21074

Equivalent with:

    n.square_udivisors.sum {|d| d**k }

square_usigma0

    square_usigma0(n)

Returns the number of unitary square divisors of n.

squfof_factor

    n.squfof_factor
    n.squfof_factor(tries)

Shanks' SQUFOF method.

The product of the factors, will give back n. However, some factors may be composite.

stirling

    stirling(n,k)

Stirling numbers of the first kind.

Aliases: stirling1

stirling2

    stirling2(n,k)

Stirling numbers of the second kind.

stirling3

    stirling3(n,k)

Stirling numbers of the third kind (also known as Lah numbers).

subfactorial

    subfactorial(n,k=0)

Number of derangements of a set with n elements having exactly k fixed points. Also known as the rencontres numbers.

    say 20.of { .subfactorial }        #=> OEIS: A000166
    say 20.of { .subfactorial(2) }     #=> OEIS: A000387

submod

    submod(a,b,m)

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

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

subsets

    n.subsets
    n.subsets(k)
    n.subsets { ... }
    n.subsets(k, { ... })

Returns an array with the subsets of the integers in the range 0..n-1, or iterates over the k-subsets when a block is given.

    say 5.subsets           # all k-subsets of 0..4
    say 5.subsets(2)        # all 2-subsets of 0..4

    5.subsets {|*a| say a }         # iterate over all k-subsets of 0..4
    5.subsets(2, {|*a| say a })     # iterate over all 2-subsets of 0..4

sum_of_squares

    sum_of_squares(n)

Returns an array of [a,b] pairs containing all the positive solutions to the equation:

    n = a^2 + b^2

Example:

    say sum_of_squares(99025)

Output:

    [[41, 312], [48, 311], [95, 300], [104, 297], [183, 256], [220, 225]]

sum_remainders

    sum_remainders(n, v)

Returns the following sum: Sum_{k=1..n} v % k, computed in O(sqrt(v)) steps.

    say 20.of {|n| sum_remainders(n, n) }        #=> OEIS: A004125
    say 20.of {|n| sum_remainders(n, n.prime) }  #=> OEIS: A099726

Negative values of v are also supported.

superfactorial

    superfactorial(n)

Returns the product of first n factorials.

    say 10.of { .superfactorial }   #=> OEIS: A000178

superprimorial

    superprimorial(n)

Returns the product of first n primorials.

    say 10.of { .superprimorial }   #=> OEIS: A006939

tan

    tan(x)

Trigonometric tangent function.

tangent_number

    tangent_number(n)

Returns the n-th tangent/zag number. (OEIS: A000182).

tanh

    tanh(x)

Hyperbolic tangent function.

times

    n.times {|k| ... }

Call a given block of code n times with k = 0,1,2,...,n-1.

    5.times {|k| say "k = #{k}" }

to_f

    x.to_f

Convert x to a floating-point value number.

Aliases: float, to_float

to_n

    x.to_n

Fixed-point function: returns x.

Aliases: to_num

to_poly

    x.to_poly

Converts x to a Polynomial object.

to_s

    x.to_s

Converts x to a String object.

Aliases: to_str

totient

    phi(n)
    totient(n)

Euler's totient function.

Aliases: euler_phi, eulerphi, euler_totient

trial_factor

    n.trial_factor(limit)

Trial division.

The product of the factors, will give back n. However, some factors may be composite.

tuples

    n.tuples(k)
    n.tuples(k, { ... })

Returns an array with the k-tuples of the integers in the range 0..n-1, or iterates over the k-tuples when a block is given.

    5.tuples(2, {|*a| say a })

Aliases: variations

tuples_with_repetition

    n.tuples_with_repetition(k)
    n.tuples_with_repetition(k, { ... })

Returns an array with the k-tuples with repetition of the integers in the range 0..n-1, or iterates over the k-tuples with repetition when a block is given.

    5.tuples_with_repetition(2, {|*a| say a })

Aliases: variations_with_repetition

udivisors

    udivisors(n)

Returns an array with the unitary divisors of n.

    say 120.udivisors   #=> [1, 3, 5, 8, 15, 24, 40, 120]

These are divisors d of n that satisfy:

    gcd(n/d, d) = 1

Aliases: unitary_divisors

uphi

    uphi(n)

The unitary totient function. (OEIS: A047994)

usigma

    usigma(n, k=1)

Returns the sum of the unitary divisors of n, each divisor raised to the power k.

usigma0

    usigma0(n)

Returns the number of unitary divisor of n.

Equivalently, the number of squarefree divisors of n.

    say usigma0(5040)   #=> 16

Aliases: squarefree_sigma0

valuation

    n.valuation(k)

Returns the number of times n is divisible by k.

    say valuation(2**32, 4)     # prints: 16

zero

    Num.zero

Returns the number 0.

znorder

    znorder(a,m)

The smallest positive integer k such that powmod(a, k, m) == 1.

Return NaN if a is not coprime to m.

znprimroot

    znprimroot(n)

The smallest primitive root of (Z/nZ)^*.