o
    oho                    @   s"  d Z ddlmZ ddlmZ ddlmZ ddlm	Z	m
Z
mZmZ ddlmZ ddlmZ ddlmZ dd	lmZmZmZ dd
lmZ ddlmZ ddlmZmZmZmZm Z m!Z! ddl"m#Z#m$Z$m%Z%m&Z& ddl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7m8Z8m9Z9m:Z:m;Z; ddl<m=Z= ddl>m?Z?m@Z@ ddlAmBZBmCZC ddlDmEZEmFZFmGZG ddlHmIZI ddlJmKZK ddlLmMZM ddlNmOZOmPZPmQZQ ddlRmSZS ddlTmUZU ddlVmWZWmXZX ddlYmZZ[ dd  Z\e
d!Z]G d"d# d#eZ^G d$d% d%eZ_G d&d' d'eZ`G d(d) d)eZaG d*d+ d+eZbG d,d- d-eZcG d.d/ d/eZdG d0d1 d1eZeG d2d3 d3eZfG d4d5 d5eZgG d6d7 d7eZhG d8d9 d9eZiG d:d; d;eZjG d<d= d=eZkG d>d? d?eZlG d@dA dAeZmG dBdC dCeZnG dDdE dEeZoG dFdG dGeZpG dHdI dIeZqG dJdK dKeZrG dLdM dMeZsG dNdO dOeZtG dPdQ dQeuZvdRZwdSZxeydTexZzdUdV Z{dtdXdYZ|edtdZd[Z}ed\d] Z~dtd^d_Zd`da Zedbdc Zddde Zedfdg ZdudidjZedkdl ZdvdmdnZG dodp dpeZdwdTdTdqdrdsZdTS )xa6  
This module implements some special functions that commonly appear in
combinatorial contexts (e.g. in power series); in particular,
sequences of rational numbers such as Bernoulli and Fibonacci numbers.

Factorials, binomial coefficients and related functions are located in
the separate 'factorials' module.
    )prod)defaultdict)Tuple)SSymbolAddDummy)cacheit)Dict)Expr)ArgumentIndexErrorFunction
expand_mul)	fuzzy_not)Mul)EIpiooRationalInteger)Eqis_leis_gtis_lt)
SYMPY_INTSremovelcmlegendrejacobi	kronecker)binomial	factorialsubfactoriallog)	Piecewise)	factorint_divisor_sigmais_carmichael find_carmichael_numbers_in_rangefind_first_n_carmichaels)_primepi)
_partition_partition_rec)isprime	is_square)bernoulli_poly
euler_polygenocchi_polycancel)MultisetPartitionTraversersympy_deprecation_warning)multisetmultiset_derangementsiterable)recurrence_memo)as_int)mpworkprec)ifibc                 C   s   t t| |d S N   )r   range)ab rF   y/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/sympy/functions/combinatorial/numbers.py_product,   s   rH   xc                   @   sX   e Zd ZdZedd Zedd Zedd Zedd	 Zed
d Z	edd Z
dS )
carmichaelaD  
    Carmichael Numbers:

    Certain cryptographic algorithms make use of big prime numbers.
    However, checking whether a big number is prime is not so easy.
    Randomized prime number checking tests exist that offer a high degree of
    confidence of accurate determination at low cost, such as the Fermat test.

    Let 'a' be a random number between $2$ and $n - 1$, where $n$ is the
    number whose primality we are testing. Then, $n$ is probably prime if it
    satisfies the modular arithmetic congruence relation:

    .. math :: a^{n-1} = 1 \pmod{n}

    (where mod refers to the modulo operation)

    If a number passes the Fermat test several times, then it is prime with a
    high probability.

    Unfortunately, certain composite numbers (non-primes) still pass the Fermat
    test with every number smaller than themselves.
    These numbers are called Carmichael numbers.

    A Carmichael number will pass a Fermat primality test to every base $b$
    relatively prime to the number, even though it is not actually prime.
    This makes tests based on Fermat's Little Theorem less effective than
    strong probable prime tests such as the Baillie-PSW primality test and
    the Miller-Rabin primality test.

    Examples
    ========

    >>> from sympy.ntheory.factor_ import find_first_n_carmichaels, find_carmichael_numbers_in_range
    >>> find_first_n_carmichaels(5)
    [561, 1105, 1729, 2465, 2821]
    >>> find_carmichael_numbers_in_range(0, 562)
    [561]
    >>> find_carmichael_numbers_in_range(0,1000)
    [561]
    >>> find_carmichael_numbers_in_range(0,2000)
    [561, 1105, 1729]

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Carmichael_number
    .. [2] https://en.wikipedia.org/wiki/Fermat_primality_test
    .. [3] https://www.jstor.org/stable/23248683?seq=1#metadata_info_tab_contents
    c                 C      t dddd t| S )Nzt
is_perfect_square is just a wrapper around sympy.ntheory.primetest.is_square
so use that directly instead.
        1.11$deprecated-carmichael-static-methodsdeprecated_since_versionactive_deprecations_target)r8   r0   nrF   rF   rG   is_perfect_squarem      zcarmichael.is_perfect_squarec                 C   s   t dddd ||  dkS )NzI
        divides can be replaced by directly testing n % p == 0.
        rL   rM   rN   r   r7   )prR   rF   rF   rG   dividesy   s   zcarmichael.dividesc                 C   rK   )Nzi
is_prime is just a wrapper around sympy.ntheory.primetest.isprime so use that
directly instead.
        rL   rM   rN   )r8   r/   rQ   rF   rF   rG   is_prime   rT   zcarmichael.is_primec                 C   rK   )Nzr
is_carmichael is just a wrapper around sympy.ntheory.factor_.is_carmichael so use that
directly instead.
        1.13%deprecated-ntheory-symbolic-functionsrN   )r8   r)   rQ   rF   rF   rG   r)      rT   zcarmichael.is_carmichaelc                 C   s   t dddd t| |S )Nz
find_carmichael_numbers_in_range is just a wrapper around sympy.ntheory.factor_.find_carmichael_numbers_in_range so use that
directly instead.
        rX   rY   rN   )r8   r*   )rI   yrF   rF   rG   r*      s   
z+carmichael.find_carmichael_numbers_in_rangec                 C   rK   )Nz
find_first_n_carmichaels is just a wrapper around sympy.ntheory.factor_.find_first_n_carmichaels so use that
directly instead.
        rX   rY   rN   )r8   r+   rQ   rF   rF   rG   r+      rT   z#carmichael.find_first_n_carmichaelsN)__name__
__module____qualname____doc__staticmethodrS   rV   rW   r)   r*   r+   rF   rF   rF   rG   rJ   :   s    2





rJ   c                   @   s^   e Zd ZdZedd Zeedeje	gdd Z
edddZd	d
 Zdd Zdd ZdS )	fibonaccia  
    Fibonacci numbers / Fibonacci polynomials

    The Fibonacci numbers are the integer sequence defined by the
    initial terms `F_0 = 0`, `F_1 = 1` and the two-term recurrence
    relation `F_n = F_{n-1} + F_{n-2}`.  This definition
    extended to arbitrary real and complex arguments using
    the formula

    .. math :: F_z = \frac{\phi^z - \cos(\pi z) \phi^{-z}}{\sqrt 5}

    The Fibonacci polynomials are defined by `F_1(x) = 1`,
    `F_2(x) = x`, and `F_n(x) = x*F_{n-1}(x) + F_{n-2}(x)` for `n > 2`.
    For all positive integers `n`, `F_n(1) = F_n`.

    * ``fibonacci(n)`` gives the `n^{th}` Fibonacci number, `F_n`
    * ``fibonacci(n, x)`` gives the `n^{th}` Fibonacci polynomial in `x`, `F_n(x)`

    Examples
    ========

    >>> from sympy import fibonacci, Symbol

    >>> [fibonacci(x) for x in range(11)]
    [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
    >>> fibonacci(5, Symbol('t'))
    t**4 + 3*t**2 + 1

    See Also
    ========

    bell, bernoulli, catalan, euler, harmonic, lucas, genocchi, partition, tribonacci

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Fibonacci_number
    .. [2] https://mathworld.wolfram.com/FibonacciNumber.html

    c                 C   s   t | S N)_ifibrQ   rF   rF   rG   _fib   s   zfibonacci._fibNc                 C   s   |d t |d    S )N_symexpandrR   prevrF   rF   rG   _fibpoly      zfibonacci._fibpolyc                 C   sz   |t ju rt jS |jr;|d u r*t|}|dk r#t j|d  t|  S t| |S |dk r2td| 	|
t|S d S )Nr   rB   zDFibonacci polynomials are defined only for positive integer indices.)r   Infinity
is_IntegerintNegativeOner`   r   rc   
ValueErrorrk   subsrg   clsrR   symrF   rF   rG   eval   s   
zfibonacci.evalc                 K   s:   ddl m}m} tj| |tj| tj|   |d S )Nr   )sqrtcos   )sympy.functionsrw   rx   r   GoldenRatioPi)selfrR   kwargsrw   rx   rF   rF   rG   _eval_rewrite_as_tractable  s   *z$fibonacci._eval_rewrite_as_tractablec                 K   sD   ddl m} d|  |d d|d | |d d |   d S )Nr   rw      ry   rB   (sympy.functions.elementary.miscellaneousrw   r}   rR   r~   rw   rF   rF   rG   _eval_rewrite_as_sqrt  s   8zfibonacci._eval_rewrite_as_sqrtc                 K   s(   t j| dt j |   dt j d  S NrB   r   )r   r{   r}   rR   r~   rF   rF   rG   _eval_rewrite_as_GoldenRatio	  s   (z&fibonacci._eval_rewrite_as_GoldenRatiora   )r[   r\   r]   r^   r_   rc   r<   r   Onerg   rk   classmethodrv   r   r   r   rF   rF   rF   rG   r`      s    )
r`   c                   @   s$   e Zd ZdZedd Zdd ZdS )lucasa  
    Lucas numbers

    Lucas numbers satisfy a recurrence relation similar to that of
    the Fibonacci sequence, in which each term is the sum of the
    preceding two. They are generated by choosing the initial
    values `L_0 = 2` and `L_1 = 1`.

    * ``lucas(n)`` gives the `n^{th}` Lucas number

    Examples
    ========

    >>> from sympy import lucas

    >>> [lucas(x) for x in range(11)]
    [2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123]

    See Also
    ========

    bell, bernoulli, catalan, euler, fibonacci, harmonic, genocchi, partition, tribonacci

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Lucas_number
    .. [2] https://mathworld.wolfram.com/LucasNumber.html

    c                 C   s2   |t ju rt jS |jrt|d t|d  S d S rA   )r   rm   rn   r`   rt   rR   rF   rF   rG   rv   4  s
   
z
lucas.evalc                 K   s8   ddl m} d|  d|d | |d d |   S )Nr   r   r   rB   ry   r   r   rF   rF   rG   r   <  s   ,zlucas._eval_rewrite_as_sqrtN)r[   r\   r]   r^   r   rv   r   rF   rF   rF   rG   r     s
    
r   c                   @   sp   e Zd ZdZeeejejejgdd Z	eeejeje
d gdd Zeddd	Zd
d Zdd ZdS )
tribonaccia  
    Tribonacci numbers / Tribonacci polynomials

    The Tribonacci numbers are the integer sequence defined by the
    initial terms `T_0 = 0`, `T_1 = 1`, `T_2 = 1` and the three-term
    recurrence relation `T_n = T_{n-1} + T_{n-2} + T_{n-3}`.

    The Tribonacci polynomials are defined by `T_0(x) = 0`, `T_1(x) = 1`,
    `T_2(x) = x^2`, and `T_n(x) = x^2 T_{n-1}(x) + x T_{n-2}(x) + T_{n-3}(x)`
    for `n > 2`.  For all positive integers `n`, `T_n(1) = T_n`.

    * ``tribonacci(n)`` gives the `n^{th}` Tribonacci number, `T_n`
    * ``tribonacci(n, x)`` gives the `n^{th}` Tribonacci polynomial in `x`, `T_n(x)`

    Examples
    ========

    >>> from sympy import tribonacci, Symbol

    >>> [tribonacci(x) for x in range(11)]
    [0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149]
    >>> tribonacci(5, Symbol('t'))
    t**8 + 3*t**5 + 3*t**2

    See Also
    ========

    bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Tribonacci_numbers
    .. [2] https://mathworld.wolfram.com/TribonacciNumber.html
    .. [3] https://oeis.org/A000073

    c                 C   s   |d |d  |d  S )Nrd   re   rF   ri   rF   rF   rG   _tribo  rl   ztribonacci._tribr   c                 C   s(   |d t |d   t d |d    S )Nr   rd   r   re   rf   ri   rF   rF   rG   	_tribpolyt  s   (ztribonacci._tribpolyNc                 C   sZ   |t ju rt jS |jr+t|}|dk rtd|d u r"t| |S | |t	|S d S )Nr   zITribonacci polynomials are defined only for non-negative integer indices.)
r   rm   rn   ro   rq   r   r   r   rr   rg   rs   rF   rF   rG   rv   y  s   
ztribonacci.evalc           
      K   s&  ddl m}m} dtj|d  d }d|dd|d   |dd|d   d }d||dd|d    |d |dd|d    d }d|d |dd|d    ||dd|d    d }||d  || ||   ||d  || ||    ||d  || ||    }	|	S )	Nr   cbrtrw   re      r   rB      !   )r   r   rw   r   ImaginaryUnit)
r}   rR   r~   r   rw   wrD   rE   cTnrF   rF   rG   r     s   0<<z tribonacci._eval_rewrite_as_sqrtc                 K   sd   ddl m} ddlm}m} |dd|d  }d| tj|  |d d|  d	  }||tj S )
Nr   floorr   iJ  f   r   r   r      )#sympy.functions.elementary.integersr   r   r   rw   r   TribonacciConstantHalf)r}   rR   r~   r   r   rw   rE   r   rF   rF   rG   #_eval_rewrite_as_TribonacciConstant  s
   &z.tribonacci._eval_rewrite_as_TribonacciConstantra   )r[   r\   r]   r^   r_   r<   r   Zeror   r   rg   r   r   rv   r   r   rF   rF   rF   rG   r   H  s    &r   c                   @   sz   e Zd ZU dZee ed< edd Ze	j
eddeddedd	d
Zddddd
ZedddZdddZdd ZdS )	bernoulliaJ  
    Bernoulli numbers / Bernoulli polynomials / Bernoulli function

    The Bernoulli numbers are a sequence of rational numbers
    defined by `B_0 = 1` and the recursive relation (`n > 0`):

    .. math :: n+1 = \sum_{k=0}^n \binom{n+1}{k} B_k

    They are also commonly defined by their exponential generating
    function, which is `\frac{x}{1 - e^{-x}}`. For odd indices > 1,
    the Bernoulli numbers are zero.

    The Bernoulli polynomials satisfy the analogous formula:

    .. math :: B_n(x) = \sum_{k=0}^n (-1)^k \binom{n}{k} B_k x^{n-k}

    Bernoulli numbers and Bernoulli polynomials are related as
    `B_n(1) = B_n`.

    The generalized Bernoulli function `\operatorname{B}(s, a)`
    is defined for any complex `s` and `a`, except where `a` is a
    nonpositive integer and `s` is not a nonnegative integer. It is
    an entire function of `s` for fixed `a`, related to the Hurwitz
    zeta function by

    .. math:: \operatorname{B}(s, a) = \begin{cases}
              -s \zeta(1-s, a) & s \ne 0 \\ 1 & s = 0 \end{cases}

    When `s` is a nonnegative integer this function reduces to the
    Bernoulli polynomials: `\operatorname{B}(n, x) = B_n(x)`. When
    `a` is omitted it is assumed to be 1, yielding the (ordinary)
    Bernoulli function which interpolates the Bernoulli numbers and is
    related to the Riemann zeta function.

    We compute Bernoulli numbers using Ramanujan's formula:

    .. math :: B_n = \frac{A(n) - S(n)}{\binom{n+3}{n}}

    where:

    .. math :: A(n) = \begin{cases} \frac{n+3}{3} &
        n \equiv 0\ \text{or}\ 2 \pmod{6} \\
        -\frac{n+3}{6} & n \equiv 4 \pmod{6} \end{cases}

    and:

    .. math :: S(n) = \sum_{k=1}^{[n/6]} \binom{n+3}{n-6k} B_{n-6k}

    This formula is similar to the sum given in the definition, but
    cuts `\frac{2}{3}` of the terms. For Bernoulli polynomials, we use
    Appell sequences.

    For `n` a nonnegative integer and `s`, `a`, `x` arbitrary complex numbers,

    * ``bernoulli(n)`` gives the nth Bernoulli number, `B_n`
    * ``bernoulli(s)`` gives the Bernoulli function `\operatorname{B}(s)`
    * ``bernoulli(n, x)`` gives the nth Bernoulli polynomial in `x`, `B_n(x)`
    * ``bernoulli(s, a)`` gives the generalized Bernoulli function
      `\operatorname{B}(s, a)`

    .. versionchanged:: 1.12
        ``bernoulli(1)`` gives `+\frac{1}{2}` instead of `-\frac{1}{2}`.
        This choice of value confers several theoretical advantages [5]_,
        including the extension to complex parameters described above
        which this function now implements. The previous behavior, defined
        only for nonnegative integers `n`, can be obtained with
        ``(-1)**n*bernoulli(n)``.

    Examples
    ========

    >>> from sympy import bernoulli
    >>> from sympy.abc import x
    >>> [bernoulli(n) for n in range(11)]
    [1, 1/2, 1/6, 0, -1/30, 0, 1/42, 0, -1/30, 0, 5/66]
    >>> bernoulli(1000001)
    0
    >>> bernoulli(3, x)
    x**3 - 3*x**2/2 + x/2

    See Also
    ========

    andre, bell, catalan, euler, fibonacci, harmonic, lucas, genocchi,
    partition, tribonacci, sympy.polys.appellseqs.bernoulli_poly

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Bernoulli_number
    .. [2] https://en.wikipedia.org/wiki/Bernoulli_polynomial
    .. [3] https://mathworld.wolfram.com/BernoulliNumber.html
    .. [4] https://mathworld.wolfram.com/BernoulliPolynomial.html
    .. [5] Peter Luschny, "The Bernoulli Manifesto",
           https://luschny.de/math/zeta/The-Bernoulli-Manifesto.html
    .. [6] Peter Luschny, "An introduction to the Bernoulli function",
           https://arxiv.org/abs/2009.06743

    argsc                 C   s   d}t t| d | d }td| d d D ]0}||t| d|   7 }|t| d d|  d | d|  9 }|td| d d| d  }q| d dkrXt| d d | }n	t| d d| }|t| d |  S )Nr   r      rB   r   	   )ro   r!   rC   r   rH   r   )rR   srD   jrF   rF   rG   _calc_bernoulli
  s   & zbernoulli._calc_bernoullirB   r   r   re      )r   rB   r   r   r   r   Nc           	      C   s,  |t ju r	| |S |jrt jS |jdu s|jdu r(|d ur&|jr&|jr&t jS d S |d u r|t ju r4t jS |j	r?|d j
r?t jS |jrt|}|dkrZt|\}}tt|t|S |d }| j| }||krl| j| S t|d |d dD ]}| |}|| j|< || j|< qv|S d S |jrt||S d S )NFrB   i  r   )r   r   is_zero
is_integeris_nonnegativern   is_nonpositiveNaNr   is_oddis_positiver   	is_Numberro   r>   bernfracr   _highest_cacherC   r   r1   )	rt   rR   rI   rU   qcasehighest_cachedirE   rF   rF   rG   rv     s>   






zbernoulli.evalc                 K   s4   ddl m} tdt|df| |d| | dfS )Nr   zetarB   T)&sympy.functions.special.zeta_functionsr   r&   r   )r}   rR   rI   r~   r   rF   rF   rG   _eval_rewrite_as_zetaD  s   (zbernoulli._eval_rewrite_as_zetac                 C   s   t dd | jD sd S | jd |}t| jdkr | jd ntj|}t|B |dkr5td}n0|dkrA|td }n$t	|rZ|dkrZ|dkrSt
|nt||}n| td| | }W d    n1 sow   Y  t||S )Nc                 s       | ]}|j V  qd S ra   	is_number.0rI   rF   rF   rG   	<genexpr>I      z(bernoulli._eval_evalf.<locals>.<genexpr>r   rB         ?)allr   
_to_mpmathlenr   r   r?   r>   mpfisintr   bernpolyr   r   _from_mpmath)r}   precrR   rI   resrF   rF   rG   _eval_evalfH  s   $
 	zbernoulli._eval_evalfra   rB   )r[   r\   r]   r^   tTupler   __annotations__r_   r   r   r   r   r   r   r   rv   r   r   rF   rF   rF   rG   r     s   
 d
"
%r   c                   @   sf   e Zd ZdZeeddgdd Zeeeje	gdd Z
edd Zedd
dZdddZd	S )bellaz  
    Bell numbers / Bell polynomials

    The Bell numbers satisfy `B_0 = 1` and

    .. math:: B_n = \sum_{k=0}^{n-1} \binom{n-1}{k} B_k.

    They are also given by:

    .. math:: B_n = \frac{1}{e} \sum_{k=0}^{\infty} \frac{k^n}{k!}.

    The Bell polynomials are given by `B_0(x) = 1` and

    .. math:: B_n(x) = x \sum_{k=1}^{n-1} \binom{n-1}{k-1} B_{k-1}(x).

    The second kind of Bell polynomials (are sometimes called "partial" Bell
    polynomials or incomplete Bell polynomials) are defined as

    .. math:: B_{n,k}(x_1, x_2,\dotsc x_{n-k+1}) =
            \sum_{j_1+j_2+j_2+\dotsb=k \atop j_1+2j_2+3j_2+\dotsb=n}
                \frac{n!}{j_1!j_2!\dotsb j_{n-k+1}!}
                \left(\frac{x_1}{1!} \right)^{j_1}
                \left(\frac{x_2}{2!} \right)^{j_2} \dotsb
                \left(\frac{x_{n-k+1}}{(n-k+1)!} \right) ^{j_{n-k+1}}.

    * ``bell(n)`` gives the `n^{th}` Bell number, `B_n`.
    * ``bell(n, x)`` gives the `n^{th}` Bell polynomial, `B_n(x)`.
    * ``bell(n, k, (x1, x2, ...))`` gives Bell polynomials of the second kind,
      `B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1})`.

    Notes
    =====

    Not to be confused with Bernoulli numbers and Bernoulli polynomials,
    which use the same notation.

    Examples
    ========

    >>> from sympy import bell, Symbol, symbols

    >>> [bell(n) for n in range(11)]
    [1, 1, 2, 5, 15, 52, 203, 877, 4140, 21147, 115975]
    >>> bell(30)
    846749014511809332450147
    >>> bell(4, Symbol('t'))
    t**4 + 6*t**3 + 7*t**2 + t
    >>> bell(6, 2, symbols('x:6')[1:])
    6*x1*x5 + 15*x2*x4 + 10*x3**2

    See Also
    ========

    bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, partition, tribonacci

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Bell_number
    .. [2] https://mathworld.wolfram.com/BellNumber.html
    .. [3] https://mathworld.wolfram.com/BellPolynomial.html

    rB   c                 C   s<   d}d}t d| D ]}|| |  | }||||  7 }q	|S rA   )rC   rR   rj   r   rD   krF   rF   rG   _bell  s   z
bell._bellc                 C   sT   d}d}t d| d D ]}|| | d  |d  }||||d   7 }qtt| S r   )rC   r   rg   r   rF   rF   rG   
_bell_poly  s   zbell._bell_polyc                 C   s   | dkr|dkrt jS | dks|dkrt jS t j}t j}td| | d D ]}||t| | |d | ||d   7 }|| |  | }q%t|S )a  
        The second kind of Bell polynomials (incomplete Bell polynomials).

        Calculated by recurrence formula:

        .. math:: B_{n,k}(x_1, x_2, \dotsc, x_{n-k+1}) =
                \sum_{m=1}^{n-k+1}
                \x_m \binom{n-1}{m-1} B_{n-m,k-1}(x_1, x_2, \dotsc, x_{n-m-k})

        where
            `B_{0,0} = 1;`
            `B_{n,0} = 0; for n \ge 1`
            `B_{0,k} = 0; for k \ge 1`

        r   rB   r   )r   r   r   rC   r   _bell_incomplete_polyr   )rR   r   symbolsr   rD   mrF   rF   rG   r     s   
zbell._bell_incomplete_polyNc                 C   s   |t ju r|d u rt jS td|js|jdu rtd|jrK|jrM|d u r/t| t	|S |d u r>| 
t	|t|S | t	|t	||}|S d S d S )NzBell polynomial is not definedFza non-negative integer expected)r   rm   rq   is_negativer   rn   r   r   r   ro   r   rr   rg   r   )rt   rR   k_symr   rrF   rF   rG   rv     s   
z	bell.evalc                 K   s^   ddl m} |d us|d ur| S |js| S tdddd}dt ||| t| |dtjf S )Nr   Sumr   T)integernonnegativerB   )sympy.concrete.summationsr   r   r   r   r"   r   rm   )r}   rR   r   r   r~   r   r   rF   rF   rG   _eval_rewrite_as_Sum  s   &zbell._eval_rewrite_as_SumNN)r[   r\   r]   r^   r_   r<   r   r   r   rg   r   r   r   rv   r   rF   rF   rF   rG   r   `  s    @

r   c                   @   s|   e Zd ZdZedddZejfddZddd	Z	dd
dZ
dddZejfddZdd ZdddZdd ZdddZdS )harmonica  
    Harmonic numbers

    The nth harmonic number is given by `\operatorname{H}_{n} =
    1 + \frac{1}{2} + \frac{1}{3} + \ldots + \frac{1}{n}`.

    More generally:

    .. math:: \operatorname{H}_{n,m} = \sum_{k=1}^{n} \frac{1}{k^m}

    As `n \rightarrow \infty`, `\operatorname{H}_{n,m} \rightarrow \zeta(m)`,
    the Riemann zeta function.

    * ``harmonic(n)`` gives the nth harmonic number, `\operatorname{H}_n`

    * ``harmonic(n, m)`` gives the nth generalized harmonic number
      of order `m`, `\operatorname{H}_{n,m}`, where
      ``harmonic(n) == harmonic(n, 1)``

    This function can be extended to complex `n` and `m` where `n` is not a
    negative integer or `m` is a nonpositive integer as

    .. math:: \operatorname{H}_{n,m} = \begin{cases} \zeta(m) - \zeta(m, n+1)
            & m \ne 1 \\ \psi(n+1) + \gamma & m = 1 \end{cases}

    Examples
    ========

    >>> from sympy import harmonic, oo

    >>> [harmonic(n) for n in range(6)]
    [0, 1, 3/2, 11/6, 25/12, 137/60]
    >>> [harmonic(n, 2) for n in range(6)]
    [0, 1, 5/4, 49/36, 205/144, 5269/3600]
    >>> harmonic(oo, 2)
    pi**2/6

    >>> from sympy import Symbol, Sum
    >>> n = Symbol("n")

    >>> harmonic(n).rewrite(Sum)
    Sum(1/_k, (_k, 1, n))

    We can evaluate harmonic numbers for all integral and positive
    rational arguments:

    >>> from sympy import S, expand_func, simplify
    >>> harmonic(8)
    761/280
    >>> harmonic(11)
    83711/27720

    >>> H = harmonic(1/S(3))
    >>> H
    harmonic(1/3)
    >>> He = expand_func(H)
    >>> He
    -log(6) - sqrt(3)*pi/6 + 2*Sum(log(sin(_k*pi/3))*cos(2*_k*pi/3), (_k, 1, 1))
                           + 3*Sum(1/(3*_k + 1), (_k, 0, 0))
    >>> He.doit()
    -log(6) - sqrt(3)*pi/6 - log(sqrt(3)/2) + 3
    >>> H = harmonic(25/S(7))
    >>> He = simplify(expand_func(H).doit())
    >>> He
    log(sin(2*pi/7)**(2*cos(16*pi/7))/(14*sin(pi/7)**(2*cos(pi/7))*cos(pi/14)**(2*sin(pi/14)))) + pi*tan(pi/14)/2 + 30247/9900
    >>> He.n(40)
    1.983697455232980674869851942390639915940
    >>> harmonic(25/S(7)).n(40)
    1.983697455232980674869851942390639915940

    We can rewrite harmonic numbers in terms of polygamma functions:

    >>> from sympy import digamma, polygamma
    >>> m = Symbol("m", integer=True, positive=True)

    >>> harmonic(n).rewrite(digamma)
    polygamma(0, n + 1) + EulerGamma

    >>> harmonic(n).rewrite(polygamma)
    polygamma(0, n + 1) + EulerGamma

    >>> harmonic(n,3).rewrite(polygamma)
    polygamma(2, n + 1)/2 + zeta(3)

    >>> simplify(harmonic(n,m).rewrite(polygamma))
    Piecewise((polygamma(0, n + 1) + EulerGamma, Eq(m, 1)),
    (-(-1)**m*polygamma(m - 1, n + 1)/factorial(m - 1) + zeta(m), True))

    Integer offsets in the argument can be pulled out:

    >>> from sympy import expand_func

    >>> expand_func(harmonic(n+4))
    harmonic(n) + 1/(n + 4) + 1/(n + 3) + 1/(n + 2) + 1/(n + 1)

    >>> expand_func(harmonic(n-4))
    harmonic(n) - 1/(n - 1) - 1/(n - 2) - 1/(n - 3) - 1/n

    Some limits can be computed as well:

    >>> from sympy import limit, oo

    >>> limit(harmonic(n), n, oo)
    oo

    >>> limit(harmonic(n, 2), n, oo)
    pi**2/6

    >>> limit(harmonic(n, 3), n, oo)
    zeta(3)

    For `m > 1`, `H_{n,m}` tends to `\zeta(m)` in the limit of infinite `n`:

    >>> m = Symbol("m", positive=True)
    >>> limit(harmonic(n, m+1), n, oo)
    zeta(m + 1)

    See Also
    ========

    bell, bernoulli, catalan, euler, fibonacci, lucas, genocchi, partition, tribonacci

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Harmonic_number
    .. [2] https://functions.wolfram.com/GammaBetaErf/HarmonicNumber/
    .. [3] https://functions.wolfram.com/GammaBetaErf/HarmonicNumber2/

    Nc                    s  ddl m}  tju r| |S  d u rtj |jrtjS  jr!|S |tju rA jr,tjS t	 tjr5tjS t
 tjr?| S d S  jrZ jrZtd  |d td   d   S |jr|jru jdu sj jdu ru tju rrtjS tjS |jrt fddtdt|d D  S d S d S )Nr   r   rB   Fc                 3   s    | ]}|   V  qd S ra   rF   r   r   r   rF   rG   r         z harmonic.eval.<locals>.<genexpr>)r   r   r   r   r   r   rm   r   r   r   r   rn   r   r   r   ComplexInfinityr   r   rC   ro   )rt   rR   r   r   rF   r   rG   rv   }  s4   

&$zharmonic.evalc                 K   sz   ddl m}m} |jr9|jr;t|d|d tj t|dftj	| ||d d||d |d   || dfS d S d S )Nr   )gamma	polygammarB   T)
'sympy.functions.special.gamma_functionsr   r   r   r   r&   r   
EulerGammar   rp   )r}   rR   r   r~   r   r   rF   rF   rG   _eval_rewrite_as_polygamma  s   (z#harmonic._eval_rewrite_as_polygammarB   c                 K      ddl m} | |S Nr   r   r   r   rewriter}   rR   r   r~   r   rF   rF   rG   _eval_rewrite_as_digamma     
z!harmonic._eval_rewrite_as_digammac                 K   r   r   r   r   rF   rF   rG   _eval_rewrite_as_trigamma  r   z"harmonic._eval_rewrite_as_trigammac                 K   s<   ddl m} tddd}|d u rtj}|||  |d|fS )Nr   r   r   Tr   rB   )r   r   r   r   r   )r}   rR   r   r~   r   r   rF   rF   rG   r     s
   zharmonic._eval_rewrite_as_Sumc                 K   sP   ddl m} ddlm} t||d tj t|df|||||d  dfS )Nr   r   digammarB   T)r   r   r   r   r&   r   r   r   )r}   rR   r   r~   r   r   rF   rF   rG   r     s
   zharmonic._eval_rewrite_as_zetac              	      s  ddl m} | jd }t| jdkr| jd nd}|tjkr|jrb|jd }||  |jrF|jrF fddt	|ddD t
 g }t| S |jrb|jrb fddt	d|dD t
 g }t| S |jr| \}}|| }	||	|  }|	jr|jr|jr||k rdd	lm}
 dd
lm} ddlm}m}m} td}||d|| |  |d|	f }d||dt | | t| |
|t| t|  |d||d td f }td |t| |  |
d|  }|| | S | S )Nr   r   r   rB   c                    s   g | ]	}t j |  qS rF   r   r   r   r   nnewrF   rG   
<listcomp>      z.harmonic._eval_expand_func.<locals>.<listcomp>re   c                    s   g | ]
}t j  |  qS rF   r   r   r   rF   rG   r         r$   r   )sinrx   cotr   )r   r   r   r   r   r   is_Addrn   r   rC   r   r   r   is_Rationalas_numer_denomr   &sympy.functions.elementary.exponentialr%   r   r   (sympy.functions.elementary.trigonometricr  rx   r  r   r   )r}   hintsr   rR   r   offresultrU   r   ur%   r   r  rx   r  r   t1t2t3rF   r   rG   _eval_expand_func  s>   


$$ $zharmonic._eval_expand_funcc           	      K   sn   ddl m} ddlm} | |}t|ts|jdddS |tj }|j	r5|||||d  jdddS d S )Nr   r   r   	tractableT)deeprB   )
r   r   r   r   r   
isinstancer   r   r   
is_nonzero)	r}   rR   r   limitvarr~   r   r   pgargrF   rF   rG   r     s   


 z#harmonic._eval_rewrite_as_tractablec                 C   s   t dd | jD sd S | jd |}t| jdkr | jd ntj|}t|r2|dk r2tjS t	| |dkrAt
|}nt|t||d  }W d    n1 sXw   Y  t||S )Nc                 s   r   ra   r   r   rF   rF   rG   r     r   z'harmonic._eval_evalf.<locals>.<genexpr>r   rB   )r   r   r   r   r   r   r>   r   r   r?   r   r   r   r   )r}   r   rR   r   r   rF   rF   rG   r     s   $
zharmonic._eval_evalfc                 C   sV   ddl m} t| jdkr| j\}}n| jd \}}|dkr)|||d |d  S t)Nr   r   r   r   rB   )r   r   r   r   r   )r}   argindexr   rR   r   rF   rF   rG   fdiff  s   zharmonic.fdiffra   r   rB   N)r[   r\   r]   r^   r   rv   r   r   r   r   r   r   r   r  r   r   r  rF   rF   rF   rG   r     s     



$
r   c                   @   s:   e Zd ZdZedddZdddZdddZd	d
 ZdS )eulera8	  
    Euler numbers / Euler polynomials / Euler function

    The Euler numbers are given by:

    .. math:: E_{2n} = I \sum_{k=1}^{2n+1} \sum_{j=0}^k \binom{k}{j}
        \frac{(-1)^j (k-2j)^{2n+1}}{2^k I^k k}

    .. math:: E_{2n+1} = 0

    Euler numbers and Euler polynomials are related by

    .. math:: E_n = 2^n E_n\left(\frac{1}{2}\right).

    We compute symbolic Euler polynomials using Appell sequences,
    but numerical evaluation of the Euler polynomial is computed
    more efficiently (and more accurately) using the mpmath library.

    The Euler polynomials are special cases of the generalized Euler function,
    related to the Genocchi function as

    .. math:: \operatorname{E}(s, a) = -\frac{\operatorname{G}(s+1, a)}{s+1}

    with the limit of `\psi\left(\frac{a+1}{2}\right) - \psi\left(\frac{a}{2}\right)`
    being taken when `s = -1`. The (ordinary) Euler function interpolating
    the Euler numbers is then obtained as
    `\operatorname{E}(s) = 2^s \operatorname{E}\left(s, \frac{1}{2}\right)`.

    * ``euler(n)`` gives the nth Euler number `E_n`.
    * ``euler(s)`` gives the Euler function `\operatorname{E}(s)`.
    * ``euler(n, x)`` gives the nth Euler polynomial `E_n(x)`.
    * ``euler(s, a)`` gives the generalized Euler function `\operatorname{E}(s, a)`.

    Examples
    ========

    >>> from sympy import euler, Symbol, S
    >>> [euler(n) for n in range(10)]
    [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0]
    >>> [2**n*euler(n,1) for n in range(10)]
    [1, 1, 0, -2, 0, 16, 0, -272, 0, 7936]
    >>> n = Symbol("n")
    >>> euler(n + 2*n)
    euler(3*n)

    >>> x = Symbol("x")
    >>> euler(n, x)
    euler(n, x)

    >>> euler(0, x)
    1
    >>> euler(1, x)
    x - 1/2
    >>> euler(2, x)
    x**2 - x
    >>> euler(3, x)
    x**3 - 3*x**2/2 + 1/4
    >>> euler(4, x)
    x**4 - 2*x**3 + x

    >>> euler(12, S.Half)
    2702765/4096
    >>> euler(12)
    2702765

    See Also
    ========

    andre, bell, bernoulli, catalan, fibonacci, harmonic, lucas, genocchi,
    partition, tribonacci, sympy.polys.appellseqs.euler_poly

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Euler_numbers
    .. [2] https://mathworld.wolfram.com/EulerNumber.html
    .. [3] https://en.wikipedia.org/wiki/Alternating_permutation
    .. [4] https://mathworld.wolfram.com/AlternatingPermutation.html

    Nc                 C   s   |j rtjS |tju r(|d u rtjd S ddlm} ||d d ||d  S |jdu s2|jdu r4d S |d u r]|j	rA|j
rAtjS |jr[ddlm} ||j}|j|dd}t|S d S |jret||S d S )	Nr   r   r   rB   Fr>   T)exact)r   r   r   rp   r|   r   r   r   r   r   r   r   r   mpmathr>   r   r   eulernumr   r2   )rt   rR   rI   r   r>   r   rF   rF   rG   rv   T  s*   


z
euler.evalc                 K   s   ddl m} |d u rS|jrStddd}tddd}|d }tj||t||tj| |d|  d| d    d| tj|  |  |d|f|dd| d f }|S |rwtddd}|t||t| d|  |tj	 ||   |d|fS d S )	Nr   r   r   Tr   r   r   rB   )
r   r   is_evenr   r   r   r!   rp   r  r   )r}   rR   rI   r~   r   r   r   EmrF   rF   rG   r   l  s&   8zeuler._eval_rewrite_as_Sumc                 K   s   |d u r"t tjd t|dfd|  t|d tj |d  dfS ddlm} t ||d d ||d  t|dft|d | |d  dfS )Nr   re   rB   Tr   r   )r&   r   r|   r   genocchir   r   r   )r}   rR   rI   r~   r   rF   rF   rG   _eval_rewrite_as_genocchiz  s   $&zeuler._eval_rewrite_as_genocchic              	   C   s\  t dd | jD sd S ddlm} t| jdkr | jd d fn| j\}}||}|d ur3||}t|i ||rQ|dkrQ|d u rJ||n|	||}nH|dkrm|d u r\|j
n||d d ||d  }n"|d u rsdn|}d|| |d|d  || |d d    }|d u r|d| 9 }W d    n1 sw   Y  t||S )	Nc                 s   r   ra   r   r   rF   rF   rG   r     r   z$euler._eval_evalf.<locals>.<genexpr>r   r  rB   re   r   r   )r   r   r  r>   r   r   r?   r   r  	eulerpolyr   r   r   r   r   )r}   r   r>   r   rI   r   rZ   rF   rF   rG   r     s&   &


 04zeuler._eval_evalfra   )	r[   r\   r]   r^   r   rv   r   r#  r   rF   rF   rF   rG   r    s    Q

r  c                   @   sp   e Zd ZdZedd ZdddZdd Zd	d
 ZdddZ	dd Z
dd Zdd Zdd Zdd Zdd ZdS )catalanaE  
    Catalan numbers

    The `n^{th}` catalan number is given by:

    .. math :: C_n = \frac{1}{n+1} \binom{2n}{n}

    * ``catalan(n)`` gives the `n^{th}` Catalan number, `C_n`

    Examples
    ========

    >>> from sympy import (Symbol, binomial, gamma, hyper,
    ...     catalan, diff, combsimp, Rational, I)

    >>> [catalan(i) for i in range(1,10)]
    [1, 2, 5, 14, 42, 132, 429, 1430, 4862]

    >>> n = Symbol("n", integer=True)

    >>> catalan(n)
    catalan(n)

    Catalan numbers can be transformed into several other, identical
    expressions involving other mathematical functions

    >>> catalan(n).rewrite(binomial)
    binomial(2*n, n)/(n + 1)

    >>> catalan(n).rewrite(gamma)
    4**n*gamma(n + 1/2)/(sqrt(pi)*gamma(n + 2))

    >>> catalan(n).rewrite(hyper)
    hyper((-n, 1 - n), (2,), 1)

    For some non-integer values of n we can get closed form
    expressions by rewriting in terms of gamma functions:

    >>> catalan(Rational(1, 2)).rewrite(gamma)
    8/(3*pi)

    We can differentiate the Catalan numbers C(n) interpreted as a
    continuous real function in n:

    >>> diff(catalan(n), n)
    (polygamma(0, n + 1/2) - polygamma(0, n + 2) + log(4))*catalan(n)

    As a more advanced example consider the following ratio
    between consecutive numbers:

    >>> combsimp((catalan(n + 1)/catalan(n)).rewrite(binomial))
    2*(2*n + 1)/(n + 2)

    The Catalan numbers can be generalized to complex numbers:

    >>> catalan(I).rewrite(gamma)
    4**I*gamma(1/2 + I)/(sqrt(pi)*gamma(2 + I))

    and evaluated with arbitrary precision:

    >>> catalan(I).evalf(20)
    0.39764993382373624267 - 0.020884341620842555705*I

    See Also
    ========

    andre, bell, bernoulli, euler, fibonacci, harmonic, lucas, genocchi,
    partition, tribonacci, sympy.functions.combinatorial.factorials.binomial

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Catalan_number
    .. [2] https://mathworld.wolfram.com/CatalanNumber.html
    .. [3] https://functions.wolfram.com/GammaBetaErf/CatalanNumber/
    .. [4] http://geometer.org/mathcircles/catalan.pdf

    c                 C   s   ddl m} |jr|js|jr(|jr(d| ||tj  |tj||d   S |jr@|jrB|d jr6tj	S |d j
rDtddS d S d S d S )Nr   r   r   r   rB   re   )r   r   rn   r   is_nonintegerr   r   r   r   r   r   r   )rt   rR   r   rF   rF   rG   rv     s   ,


zcatalan.evalrB   c                 C   sP   ddl m} ddlm} | jd }t||d|tj |d|d  |d  S )Nr   r$   r   r   r   )r  r%   r   r   r   r%  r   r   )r}   r  r%   r   rR   rF   rF   rG   r    s   
.zcatalan.fdiffc                 K   s   t d| ||d  S Nr   rB   )r!   r   rF   rF   rG   _eval_rewrite_as_binomial  s   z!catalan._eval_rewrite_as_binomialc                 K   s    t d| t |d t |  S r(  r"   r   rF   rF   rG   _eval_rewrite_as_factorial  s    z"catalan._eval_rewrite_as_factorialTc                 K   s8   ddl m} d| ||tj  |tj||d   S )Nr   r&  r   r   )r   r   r   r   )r}   rR   	piecewiser~   r   rF   rF   rG   _eval_rewrite_as_gamma  s   ,zcatalan._eval_rewrite_as_gammac                 K   s$   ddl m} |d| | gdgdS )Nr   )hyperrB   r   )sympy.functions.special.hyperr.  )r}   rR   r~   r.  rF   rF   rG   _eval_rewrite_as_hyper  s   zcatalan._eval_rewrite_as_hyperc                 K   sB   ddl m} |jr|js| S tdddd}||| | |d|fS )Nr   )Productr   T)r   positiver   )sympy.concrete.productsr1  r   r   r   )r}   rR   r~   r1  r   rF   rF   rG   _eval_rewrite_as_Product  s
   z catalan._eval_rewrite_as_Productc                 C   s$   | j d jr| j d jrdS d S d S Nr   Tr   r   r   r}   rF   rF   rG   _eval_is_integer  s   zcatalan._eval_is_integerc                 C      | j d jrdS d S r5  r   r   r7  rF   rF   rG   _eval_is_positive     zcatalan._eval_is_positivec                 C   s(   | j d jr| j d d jrdS d S d S )Nr   r   T)r   r   r   r7  rF   rF   rG   _eval_is_composite   s   zcatalan._eval_is_compositec                 C   s,   ddl m} | jd jr| ||S d S )Nr   r&  )r   r   r   r   r   r   )r}   r   r   rF   rF   rG   r   $  s   zcatalan._eval_evalfNr   )T)r[   r\   r]   r^   r   rv   r  r)  r+  r-  r0  r4  r8  r;  r=  r   rF   rF   rF   rG   r%    s    O


r%  c                   @   sj   e Zd ZdZedddZdddZddd	Zd
d Zdd Z	dd Z
dd Zdd Zdd Zdd ZdS )r"  aY  
    Genocchi numbers / Genocchi polynomials / Genocchi function

    The Genocchi numbers are a sequence of integers `G_n` that satisfy the
    relation:

    .. math:: \frac{-2t}{1 + e^{-t}} = \sum_{n=0}^\infty \frac{G_n t^n}{n!}

    They are related to the Bernoulli numbers by

    .. math:: G_n = 2 (1 - 2^n) B_n

    and generalize like the Bernoulli numbers to the Genocchi polynomials and
    function as

    .. math:: \operatorname{G}(s, a) = 2 \left(\operatorname{B}(s, a) -
              2^s \operatorname{B}\left(s, \frac{a+1}{2}\right)\right)

    .. versionchanged:: 1.12
        ``genocchi(1)`` gives `-1` instead of `1`.

    Examples
    ========

    >>> from sympy import genocchi, Symbol
    >>> [genocchi(n) for n in range(9)]
    [0, -1, -1, 0, 1, 0, -3, 0, 17]
    >>> n = Symbol('n', integer=True, positive=True)
    >>> genocchi(2*n + 1)
    0
    >>> x = Symbol('x')
    >>> genocchi(4, x)
    -4*x**3 + 6*x**2 - 1

    See Also
    ========

    bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, partition, tribonacci
    sympy.polys.appellseqs.genocchi_poly

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Genocchi_number
    .. [2] https://mathworld.wolfram.com/GenocchiNumber.html
    .. [3] Peter Luschny, "An introduction to the Bernoulli function",
           https://arxiv.org/abs/2009.06743

    Nc                 C   s   |t ju r	| |S |jdu s|jdu rd S |d u r7|jr$|d jr$t jS |jr5ddt d|   t| S d S |jr?t	||S d S )NFrB   r   )
r   r   r   r   r   r   r   r   r   r3   )rt   rR   rI   rF   rF   rG   rv   d  s   

zgenocchi.evalrB   c                 K   sX   |dkr|j r|jrddtd|   t| S dt||d| t||d d    S r   )r   r   r   r   )r}   rR   rI   r~   rF   rF   rG   _eval_rewrite_as_bernoullit  s   (z#genocchi._eval_rewrite_as_bernoullic                 K   s"   ddl m} d| |d| | S )Nr   )dirichlet_etard   rB   )r   r?  )r}   rR   rI   r~   r?  rF   rF   rG   _eval_rewrite_as_dirichlet_etay  s   z'genocchi._eval_rewrite_as_dirichlet_etac                 C   sB   t | jdkr| jd dkrd S | jd }|jr|jrdS d S d S )NrB   r   T)r   r   r   r   r}   rR   rF   rF   rG   r8  }  s   
zgenocchi._eval_is_integerc                 C   s\   t | jdkr| jd dkrd S | jd }|jr*|jr,|jr%t|d jS |d jS d S d S )NrB   r   r   )r   r   r   r   r   r   r   rA  rF   rF   rG   _eval_is_negative  s   

zgenocchi._eval_is_negativec                 C   sX   t | jdkr| jd dkrd S | jd }|jr(|jr*|js!|jr#dS |d jS d S d S )NrB   r   Fr   )r   r   r   r   r   r   r   rA  rF   rF   rG   r;    s   

zgenocchi._eval_is_positivec                 C   sT   t | jdkr| jd dkrd S | jd }|jr&|jr(|jr!|jS |d jS d S d S NrB   r   )r   r   r   r   r   r   r   rA  rF   rF   rG   _eval_is_even  s   

zgenocchi._eval_is_evenc                 C   s\   t | jdkr| jd dkrd S | jd }|jr*|jr,|jr#t|jS t|d jS d S d S rC  )r   r   r   r   r   r   r   r   rA  rF   rF   rG   _eval_is_odd  s   

zgenocchi._eval_is_oddc                 C   s4   t | jdkr| jd dkrd S | jd }|d jS )NrB   r      )r   r   r   rA  rF   rF   rG   _eval_is_prime  s   

zgenocchi._eval_is_primec                 C   s(   t dd | jD r| t|S d S )Nc                 s   r   ra   r   r   rF   rF   rG   r     r   z'genocchi._eval_evalf.<locals>.<genexpr>)r   r   r   r   r   )r}   r   rF   rF   rG   r     s   zgenocchi._eval_evalfra   r   )r[   r\   r]   r^   r   rv   r>  r@  r8  rB  r;  rD  rE  rG  r   rF   rF   rF   rG   r"  1  s    2

					r"  c                   @   sD   e Zd ZdZedd Zdd Zdd Zdd	 Zd
d Z	dd Z
dS )andrea  
    Andre numbers / Andre function

    The Andre number `\mathcal{A}_n` is Luschny's name for half the number of
    *alternating permutations* on `n` elements, where a permutation is alternating
    if adjacent elements alternately compare "greater" and "smaller" going from
    left to right. For example, `2 < 3 > 1 < 4` is an alternating permutation.

    This sequence is A000111 in the OEIS, which assigns the names *up/down numbers*
    and *Euler zigzag numbers*. It satisfies a recurrence relation similar to that
    for the Catalan numbers, with `\mathcal{A}_0 = 1` and

    .. math:: 2 \mathcal{A}_{n+1} = \sum_{k=0}^n \binom{n}{k} \mathcal{A}_k \mathcal{A}_{n-k}

    The Bernoulli and Euler numbers are signed transformations of the odd- and
    even-indexed elements of this sequence respectively:

    .. math :: \operatorname{B}_{2k} = \frac{2k \mathcal{A}_{2k-1}}{(-4)^k - (-16)^k}

    .. math :: \operatorname{E}_{2k} = (-1)^k \mathcal{A}_{2k}

    Like the Bernoulli and Euler numbers, the Andre numbers are interpolated by the
    entire Andre function:

    .. math :: \mathcal{A}(s) = (-i)^{s+1} \operatorname{Li}_{-s}(i) +
            i^{s+1} \operatorname{Li}_{-s}(-i) = \\ \frac{2 \Gamma(s+1)}{(2\pi)^{s+1}}
            (\zeta(s+1, 1/4) - \zeta(s+1, 3/4) \cos{\pi s})

    Examples
    ========

    >>> from sympy import andre, euler, bernoulli
    >>> [andre(n) for n in range(11)]
    [1, 1, 1, 2, 5, 16, 61, 272, 1385, 7936, 50521]
    >>> [(-1)**k * andre(2*k) for k in range(7)]
    [1, -1, 5, -61, 1385, -50521, 2702765]
    >>> [euler(2*k) for k in range(7)]
    [1, -1, 5, -61, 1385, -50521, 2702765]
    >>> [andre(2*k-1) * (2*k) / ((-4)**k - (-16)**k) for k in range(1, 8)]
    [1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6]
    >>> [bernoulli(2*k) for k in range(1, 8)]
    [1/6, -1/30, 1/42, -1/30, 5/66, -691/2730, 7/6]

    See Also
    ========

    bernoulli, catalan, euler, sympy.polys.appellseqs.andre_poly

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Alternating_permutation
    .. [2] https://mathworld.wolfram.com/EulerZigzagNumber.html
    .. [3] Peter Luschny, "An introduction to the Bernoulli function",
           https://arxiv.org/abs/2009.06743
    c                 C   s   |t ju rt jS |t ju rt jS |jrt jS |dkrtd S |dkr(dt j S |jrY|jr7|j	r7t
t|S |jr[ddlm} | d }t| tdd|  d|  ||  S d S d S )Nre   r   rd   r   r   rB   r   )r   r   rm   r   r   r%   Catalanrn   r   r   absr  r   r   r   r   r   )rt   rR   r   r   rF   rF   rG   rv     s&   




(z
andre.evalc                 K   sz   ddl m} ddlm} ddlm} d||d  dt |d   ||d tjd |t| ||d tdd    S )	Nr   )rx   r&  r   r   rB   r   r   )	r  rx   r   r   r   r   r   r   r   )r}   r   r~   rx   r   r   rF   rF   rG   r     s   4zandre._eval_rewrite_as_zetac                 K   s@   ddl m} t |d  || t t|d  || t   S )Nr   )polylogrB   )r   rK  r   )r}   r   r~   rK  rF   rF   rG   _eval_rewrite_as_polylog  s   4zandre._eval_rewrite_as_polylogc                 C   s"   | j d }|jr|jrdS d S d S r5  r6  rA  rF   rF   rG   r8    s   
zandre._eval_is_integerc                 C   r9  r5  r:  r7  rF   rF   rG   r;    r<  zandre._eval_is_positivec              	   C   s   | j d jsd S | j d |d }t|d & t|d t|d }}dt| | ||| f }W d    n1 sAw   Y  t	||S )Nr      r   )
r   r   r   r?   r>   sinpicospi	dirichletr   r   )r}   r   r   spcpr   rF   rF   rG   r     s    zandre._eval_evalfN)r[   r\   r]   r^   r   rv   r   rL  r8  r;  r   rF   rF   rF   rG   rH    s    9
rH  c                   @   s,   e Zd ZdZdZdZedd Zdd ZdS )	partitionaN  
    Partition numbers

    The Partition numbers are a sequence of integers `p_n` that represent the
    number of distinct ways of representing `n` as a sum of natural numbers
    (with order irrelevant). The generating function for `p_n` is given by:

    .. math:: \sum_{n=0}^\infty p_n x^n = \prod_{k=1}^\infty (1 - x^k)^{-1}

    Examples
    ========

    >>> from sympy import partition, Symbol
    >>> [partition(n) for n in range(9)]
    [1, 1, 2, 3, 5, 7, 11, 15, 22]
    >>> n = Symbol('n', integer=True, negative=True)
    >>> partition(n)
    0

    See Also
    ========

    bell, bernoulli, catalan, euler, fibonacci, harmonic, lucas, genocchi, tribonacci

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Partition_(number_theory%29
    .. [2] https://en.wikipedia.org/wiki/Pentagonal_number_theorem

    Tc                 C   sZ   |j du r	td|jdu rtjS |jdu s|tju rtjS |jdu r+ttt	|S d S )NFn should be an integerT)
r   	TypeErrorr   r   r   r   r   rn   r-   r=   r   rF   rF   rG   rv   S  s   


zpartition.evalc                 C   s   | j d jdu r
dS d S r5  r:  r7  rF   rF   rG   r;  ^  s   zpartition._eval_is_positiveN)	r[   r\   r]   r^   r   r   r   rv   r;  rF   rF   rF   rG   rS  0  s    

rS  c                   @   *   e Zd ZdZdZdZeejfddZ	dS )divisor_sigmaaF  
    Calculate the divisor function `\sigma_k(n)` for positive integer n

    ``divisor_sigma(n, k)`` is equal to ``sum([x**k for x in divisors(n)])``

    If n's prime factorization is:

    .. math ::
        n = \prod_{i=1}^\omega p_i^{m_i},

    then

    .. math ::
        \sigma_k(n) = \prod_{i=1}^\omega (1+p_i^k+p_i^{2k}+\cdots
        + p_i^{m_ik}).

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import divisor_sigma
    >>> divisor_sigma(18, 0)
    6
    >>> divisor_sigma(39, 1)
    56
    >>> divisor_sigma(12, 2)
    210
    >>> divisor_sigma(37)
    38

    See Also
    ========

    sympy.ntheory.factor_.divisor_count, totient, sympy.ntheory.factor_.divisors, sympy.ntheory.factor_.factorint

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Divisor_function

    Tc                    s   |j du r	td|jdu rtd j du rtd jdu r$td|jdu r/d|   S |tju r7tjS |jdu rr j	du rNt
dd	 t| D  S  jdu r^ttt|t S  j	du rtt
 fd
d	t| D  S d S d S )NFrT  n should be a positive integerk should be an integer!k should be a nonnegative integerTrB   c                 S   s   g | ]}|d  qS r   rF   )r   erF   rF   rG   r         z&divisor_sigma.eval.<locals>.<listcomp>c                    s4   g | ]\}}t | |d    d  |  d   qS r   r4   r   rU   r[  r   rF   rG   r     s   4 )r   rU  r   rq   r   rW   r   r   rn   r   r   r'   valuesr(   r=   itemsrt   rR   r   rF   r^  rG   rv     s*   









zdivisor_sigma.evalN
r[   r\   r]   r^   r   r   r   r   r   rv   rF   rF   rF   rG   rW  c  s    (rW  c                   @   rV  )udivisor_sigmaa  
    Calculate the unitary divisor function `\sigma_k^*(n)` for positive integer n

    ``udivisor_sigma(n, k)`` is equal to ``sum([x**k for x in udivisors(n)])``

    If n's prime factorization is:

    .. math ::
        n = \prod_{i=1}^\omega p_i^{m_i},

    then

    .. math ::
        \sigma_k^*(n) = \prod_{i=1}^\omega (1+ p_i^{m_ik}).

    Parameters
    ==========

    k : power of divisors in the sum

        for k = 0, 1:
        ``udivisor_sigma(n, 0)`` is equal to ``udivisor_count(n)``
        ``udivisor_sigma(n, 1)`` is equal to ``sum(udivisors(n))``

        Default for k is 1.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import udivisor_sigma
    >>> udivisor_sigma(18, 0)
    4
    >>> udivisor_sigma(74, 1)
    114
    >>> udivisor_sigma(36, 3)
    47450
    >>> udivisor_sigma(111)
    152

    See Also
    ========

    sympy.ntheory.factor_.divisor_count, totient, sympy.ntheory.factor_.divisors,
    sympy.ntheory.factor_.udivisors, sympy.ntheory.factor_.udivisor_count, divisor_sigma,
    sympy.ntheory.factor_.factorint

    References
    ==========

    .. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html

    Tc                    s   |j du r	td|jdu rtd j du rtd jdu r$td|jdu r/d|   S |jrAt fdd	t|	 D  S d S )
NFrT  rX  rY  rZ  TrB   c                    s    g | ]\}}d | |   qS r   rF   r]  r^  rF   rG   r          z'udivisor_sigma.eval.<locals>.<listcomp>)
r   rU  r   rq   r   rW   rn   r   r'   r`  ra  rF   r^  rG   rv     s   




zudivisor_sigma.evalNrb  rF   rF   rF   rG   rc    s    4rc  c                   @   $   e Zd ZdZdZdZedd ZdS )legendre_symbola  
    Returns the Legendre symbol `(a / p)`.

    For an integer ``a`` and an odd prime ``p``, the Legendre symbol is
    defined as

    .. math ::
        \genfrac(){}{}{a}{p} = \begin{cases}
             0 & \text{if } p \text{ divides } a\\
             1 & \text{if } a \text{ is a quadratic residue modulo } p\\
            -1 & \text{if } a \text{ is a quadratic nonresidue modulo } p
        \end{cases}

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import legendre_symbol
    >>> [legendre_symbol(i, 7) for i in range(7)]
    [0, 1, 1, -1, 1, -1, -1]
    >>> sorted(set([i**2 % 7 for i in range(7)]))
    [0, 1, 2, 4]

    See Also
    ========

    sympy.ntheory.residue_ntheory.is_quad_residue, jacobi_symbol

    TFc                 C   s   |j du r	td|j du rtd|jdu s|jdu r td|| jdu r*tjS |tju r2tjS |j	du rG|j	du rItt
t|t|S d S d S )NFa should be an integerzp should be an integerz p should be an odd prime integerT)r   rU  rW   r   rq   r   r   r   r   rn   r   r=   )rt   rD   rU   rF   rF   rG   rv     s   


zlegendre_symbol.evalNr[   r\   r]   r^   r   rW   r   rv   rF   rF   rF   rG   rf    s    rf  c                   @   re  )jacobi_symbola  
    Returns the Jacobi symbol `(m / n)`.

    For any integer ``m`` and any positive odd integer ``n`` the Jacobi symbol
    is defined as the product of the Legendre symbols corresponding to the
    prime factors of ``n``:

    .. math ::
        \genfrac(){}{}{m}{n} =
            \genfrac(){}{}{m}{p^{1}}^{\alpha_1}
            \genfrac(){}{}{m}{p^{2}}^{\alpha_2}
            ...
            \genfrac(){}{}{m}{p^{k}}^{\alpha_k}
            \text{ where } n =
                p_1^{\alpha_1}
                p_2^{\alpha_2}
                ...
                p_k^{\alpha_k}

    Like the Legendre symbol, if the Jacobi symbol `\genfrac(){}{}{m}{n} = -1`
    then ``m`` is a quadratic nonresidue modulo ``n``.

    But, unlike the Legendre symbol, if the Jacobi symbol
    `\genfrac(){}{}{m}{n} = 1` then ``m`` may or may not be a quadratic residue
    modulo ``n``.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import jacobi_symbol, legendre_symbol
    >>> from sympy import S
    >>> jacobi_symbol(45, 77)
    -1
    >>> jacobi_symbol(60, 121)
    1

    The relationship between the ``jacobi_symbol`` and ``legendre_symbol`` can
    be demonstrated as follows:

    >>> L = legendre_symbol
    >>> S(45).factors()
    {3: 2, 5: 1}
    >>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1
    True

    See Also
    ========

    sympy.ntheory.residue_ntheory.is_quad_residue, legendre_symbol

    TFc                 C   s   |j du r	td|j du rtd|jdu s|jdu r td|tju s*|tju r-tjS || jdu r7tjS |j	du rL|j	du rNtt
t|t|S d S d S )NFzm should be an integerrT  z#n should be an odd positive integerT)r   rU  r   r   rq   r   r   r   r   rn   r   r=   )rt   r   rR   rF   rF   rG   rv   U  s   

zjacobi_symbol.evalNrh  rF   rF   rF   rG   ri    s    3ri  c                   @   re  )kronecker_symbola  
    Returns the Kronecker symbol `(a / n)`.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import kronecker_symbol
    >>> kronecker_symbol(45, 77)
    -1
    >>> kronecker_symbol(13, -120)
    1

    See Also
    ========

    jacobi_symbol, legendre_symbol

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Kronecker_symbol

    TFc                 C   sp   |j du r	td|j du rtd|tju s|tju rtjS |jdu r4|jdu r6ttt|t|S d S d S )NFrg  rT  T)r   rU  r   r   rn   r    r=   )rt   rD   rR   rF   rF   rG   rv     s   

zkronecker_symbol.evalNrh  rF   rF   rF   rG   rj  e  s    rj  c                   @   re  )mobiusa  
    Mobius function maps natural number to {-1, 0, 1}

    It is defined as follows:
        1) `1` if `n = 1`.
        2) `0` if `n` has a squared prime factor.
        3) `(-1)^k` if `n` is a square-free positive integer with `k`
           number of prime factors.

    It is an important multiplicative function in number theory
    and combinatorics.  It has applications in mathematical series,
    algebraic number theory and also physics (Fermion operator has very
    concrete realization with Mobius Function model).

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import mobius
    >>> mobius(13*7)
    1
    >>> mobius(1)
    1
    >>> mobius(13*7*5)
    -1
    >>> mobius(13**2)
    0

    Even in the case of a symbol, if it clearly contains a squared prime factor, it will be zero.

    >>> from sympy import Symbol
    >>> n = Symbol("n", integer=True, positive=True)
    >>> mobius(4*n)
    0
    >>> mobius(n**2)
    0

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius_function
    .. [2] Thomas Koshy "Elementary Number Theory with Applications"
    .. [3] https://oeis.org/A008683

    TFc                 C   s  |j du r	td|jdu rtd|jdu rtjS |tju r"tjS d }dd t	|D D ]\\}}|j du r|jdu r|j du r|jdu rt
tj|}|du rTtj}q.|jdu rt|}tdd | D rltj}q.|du rt|d rytjntj}|d u r|}q.||9 }q. d S |S )	NFrT  rX  Tc                 s   s    | ]}|  V  qd S ra   )as_base_expr   _rF   rF   rG   r         zmobius.eval.<locals>.<genexpr>c                 s   s    | ]}|d kV  qdS r  rF   r   vrF   rF   rG   r     ro  r   )r   rU  r   rq   rW   r   rp   r   r   	make_argsr   r   rn   r'   anyr_  r   )rt   rR   r  r   r[  ltfactorsr   rF   rF   rG   rv     s6   




zmobius.evalNrh  rF   rF   rF   rG   rk    s    ,rk  c                   @   $   e Zd ZdZdZdZedd ZdS )primenuaH  
    Calculate the number of distinct prime factors for a positive integer n.

    If n's prime factorization is:

    .. math ::
        n = \prod_{i=1}^k p_i^{m_i},

    then ``primenu(n)`` or `\nu(n)` is:

    .. math ::
        \nu(n) = k.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import primenu
    >>> primenu(1)
    0
    >>> primenu(30)
    3

    See Also
    ========

    sympy.ntheory.factor_.factorint

    References
    ==========

    .. [1] https://mathworld.wolfram.com/PrimeFactor.html
    .. [2] https://oeis.org/A001221

    Tc                 C   sb   |j du r	td|jdu rtd|jdu rtjS |tju r"tjS |jdu r/tt	t
|S d S NFrT  rX  T)r   rU  r   rq   rW   r   r   r   rn   r   r'   r   rF   rF   rG   rv     s   




zprimenu.evalNr[   r\   r]   r^   r   r   r   rv   rF   rF   rF   rG   rw    s    "rw  c                   @   rv  )
primeomegaa}  
    Calculate the number of prime factors counting multiplicities for a
    positive integer n.

    If n's prime factorization is:

    .. math ::
        n = \prod_{i=1}^k p_i^{m_i},

    then ``primeomega(n)``  or `\Omega(n)` is:

    .. math ::
        \Omega(n) = \sum_{i=1}^k m_i.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import primeomega
    >>> primeomega(1)
    0
    >>> primeomega(20)
    3

    See Also
    ========

    sympy.ntheory.factor_.factorint

    References
    ==========

    .. [1] https://mathworld.wolfram.com/PrimeFactor.html
    .. [2] https://oeis.org/A001222

    Tc                 C   sf   |j du r	td|jdu rtd|jdu rtjS |tju r"tjS |jdu r1tt	t
| S d S rx  )r   rU  r   rq   rW   r   r   r   rn   sumr'   r_  r   rF   rF   rG   rv   7  s   




zprimeomega.evalNry  rF   rF   rF   rG   rz        #rz  c                   @   rv  )totientay  
    Calculate the Euler totient function phi(n)

    ``totient(n)`` or `\phi(n)` is the number of positive integers `\leq` n
    that are relatively prime to n.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import totient
    >>> totient(1)
    1
    >>> totient(25)
    20
    >>> totient(45) == totient(5)*totient(9)
    True

    See Also
    ========

    sympy.ntheory.factor_.divisor_count

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Euler%27s_totient_function
    .. [2] https://mathworld.wolfram.com/TotientFunction.html
    .. [3] https://oeis.org/A000010

    Tc                 C   s   |j du r	td|jdu rtd|tju rtjS |jdu r#|d S t|tr5tt	dd |
 D S |jdu rItt	dd t|
 D S d S )	NFrT  rX  TrB   c                 s   (    | ]\}}||d   |d   V  qdS r  rF   r   rU   r   rF   rF   rG   r   r     & ztotient.eval.<locals>.<genexpr>c                 s   r~  r  rF   r  rF   rF   rG   r   t  r  )r   rU  r   rq   r   r   rW   r  r
   r   r`  rn   r'   r   rF   rF   rG   rv   g  s   





ztotient.evalNr[   r\   r]   r^   r   r   r   rv   rF   rF   rF   rG   r}  E      r}  c                   @   rv  )reduced_totienta  
    Calculate the Carmichael reduced totient function lambda(n)

    ``reduced_totient(n)`` or `\lambda(n)` is the smallest m > 0 such that
    `k^m \equiv 1 \mod n` for all k relatively prime to n.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import reduced_totient
    >>> reduced_totient(1)
    1
    >>> reduced_totient(8)
    2
    >>> reduced_totient(30)
    4

    See Also
    ========

    totient

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Carmichael_function
    .. [2] https://mathworld.wolfram.com/CarmichaelFunction.html
    .. [3] https://oeis.org/A002322

    Tc                 C   s
  |j du r	td|jdu rtd|tju rtjS |jdu r#|d S t|trSd}d|v r@d|d k r<d|d d > n|d }tt	t
|gdd | D R  S |jdu rtt
|d\}}|sfd}n
d|k rpd|d > }tt	|gd	d t| D R  S d S )
NFrT  rX  TrB   r   c                 s   s<    | ]\}}|d krt |d t |t |d   V  qdS )r   rB   N)ro   r  rF   rF   rG   r     s   : z'reduced_totient.eval.<locals>.<genexpr>c                 s   s(    | ]\}}|d  ||d    V  qdS r  rF   r  rF   rF   rG   r     r  )r   rU  r   rq   r   r   rW   r  r
   r   ro   r`  rn   r   r'   )rt   rR   trF   rF   rG   rv     s*   




$&
&zreduced_totient.evalNr  rF   rF   rF   rG   r  w  r  r  c                   @   rv  )primepia   Represents the prime counting function pi(n) = the number
    of prime numbers less than or equal to n.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import primepi
    >>> from sympy import prime, prevprime, isprime
    >>> primepi(25)
    9

    So there are 9 primes less than or equal to 25. Is 25 prime?

    >>> isprime(25)
    False

    It is not. So the first prime less than 25 must be the
    9th prime:

    >>> prevprime(25) == prime(9)
    True

    See Also
    ========

    sympy.ntheory.primetest.isprime : Test if n is prime
    sympy.ntheory.generate.primerange : Generate all primes in a given range
    sympy.ntheory.generate.prime : Return the nth prime

    References
    ==========

    .. [1] https://oeis.org/A000720

    Tc                 C   sx   |t ju rt jS |t ju rt jS |jdu rtdt|t ddu r%t jS zt|}W n
 ty5   Y d S w t t|S )NFzn should be a realr   T)	r   rm   NegativeInfinityr   is_realrU  r   ro   r,   r   rF   rF   rG   rv     s   


zprimepi.evalNry  rF   rF   rF   rG   r    r|  r  c                   @   s   e Zd ZdS )_MultisetHistogramN)r[   r\   r]   rF   rF   rF   rG   r    s    r  re   rd   Nc           	         s   t  tr2tdd   D stt  }t fdd D }t fdd D ||g S t  t }t	|}t	 }||krSdg| ||g  t S tt
|t|}tt
t|d| } D ]}|||   d7  < qit|S )a6  Return tuple used in permutation and combination counting. Input
    is a dictionary giving items with counts as values or a sequence of
    items (which need not be sorted).

    The data is stored in a class deriving from tuple so it is easily
    recognized and so it can be converted easily to a list.
    c                 s   s"    | ]}t |to|d kV  qdS )r   N)r  ro   rp  rF   rF   rG   r   	  s     z&_multiset_histogram.<locals>.<genexpr>c                 3   s     | ]} | d krdV  qdS )r   rB   NrF   r   rQ   rF   rG   r   	  s    c                    s    g | ]} | d kr | qS r   rF   r   rQ   rF   rG   r   	  rd  z'_multiset_histogram.<locals>.<listcomp>rB   r  )r  dictr   r_  rq   r{  r  listsetr   ziprC   _multiset_histogram)	rR   totr`  r   lenslennr   dr   rF   rQ   rG   r    s$   
r  Fc                 C   sD   zt | } W n ty   ttt| || Y S w tt| ||S )a`  Return the number of permutations of ``n`` items taken ``k`` at a time.

    Possible values for ``n``:

        integer - set of length ``n``

        sequence - converted to a multiset internally

        multiset - {element: multiplicity}

    If ``k`` is None then the total of all permutations of length 0
    through the number of items represented by ``n`` will be returned.

    If ``replacement`` is True then a given item can appear more than once
    in the ``k`` items. (For example, for 'ab' permutations of 2 would
    include 'aa', 'ab', 'ba' and 'bb'.) The multiplicity of elements in
    ``n`` is ignored when ``replacement`` is True but the total number
    of elements is considered since no element can appear more times than
    the number of elements in ``n``.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import nP
    >>> from sympy.utilities.iterables import multiset_permutations, multiset
    >>> nP(3, 2)
    6
    >>> nP('abc', 2) == nP(multiset('abc'), 2) == 6
    True
    >>> nP('aab', 2)
    3
    >>> nP([1, 2, 2], 2)
    3
    >>> [nP(3, i) for i in range(4)]
    [1, 3, 6, 6]
    >>> nP(3) == sum(_)
    True

    When ``replacement`` is True, each item can have multiplicity
    equal to the length represented by ``n``:

    >>> nP('aabc', replacement=True)
    121
    >>> [len(list(multiset_permutations('aaaabbbbcccc', i))) for i in range(5)]
    [1, 3, 9, 27, 81]
    >>> sum(_)
    121

    See Also
    ========
    sympy.utilities.iterables.multiset_permutations

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Permutation

    )r=   rq   r   _nPr  )rR   r   replacementrF   rF   rG   nP	  s   ;r  c                    s  |dkrdS t  trB|d u rt fddt d D S r% | S | kr+dS | kr3t|S |dkr9 S t | d  S t  tr|d u r]t fddt t d D S re t | S | t krzt|t	dd  t
 D  S | t krdS |dkr t S d}t  tt t
 D ]\} | sq t  d8  <  | dkrd |<  t  d8  < |tt |d 7 } t  d7  < d |< n |  d8  < |tt |d 7 } |  d7  <  t  d7  < q|S d S )Nr   rB   c                 3       | ]	}t  |V  qd S ra   r  r   rR   r  rF   rG   r   `	      z_nP.<locals>.<genexpr>c                 3   r  ra   r  r   r  rF   rG   r   n	  r  c                 S   s   g | ]
}|d krt |qS r   r*  r   rF   rF   rG   r   r	  r  z_nP.<locals>.<listcomp>)r  r   r{  rC   r"   rH   r  _N_ITEMSr   _Mr  r   r  )rR   r   r  r  r   rF   r  rG   r  X	  sV   
 
$
r  c                 C   s*  t | } t| }|d d }dg|  d  }|d|t|   |d| }| rm|  }|d }|dd }tdt|t|D ]}||  ||d  7  < qBt||D ]}||  ||d  |||   7  < qV| s*t t|}|d r||| }n||dd< tt	}	t
|D ]\}}
|
|	|< q|	S )a  for n = (m1, m2, .., mk) return the coefficients of the polynomial,
    prod(sum(x**i for i in range(nj + 1)) for nj in n); i.e. the coefficients
    of the product of AOPs (all-one polynomials) or order given in n.  The
    resulting coefficient corresponding to x**r is the number of r-length
    combinations of sum(n) elements with multiplicities given in n.
    The coefficients are given as a default dictionary (so if a query is made
    for a key that is not present, 0 will be returned).

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import _AOP_product
    >>> from sympy.abc import x
    >>> n = (2, 2, 3)  # e.g. aabbccc
    >>> prod = ((x**2 + x + 1)*(x**2 + x + 1)*(x**3 + x**2 + x + 1)).expand()
    >>> c = _AOP_product(n); dict(c)
    {0: 1, 1: 3, 2: 6, 3: 8, 4: 8, 5: 6, 6: 3, 7: 1}
    >>> [c[i] for i in range(8)] == [prod.coeff(x, i) for i in range(8)]
    True

    The generating poly used here is the same as that listed in
    https://tinyurl.com/cep849r, but in a refactored form.

    r   rB   r  Nre   )r  r{  popextendr   rC   minreversedr   ro   	enumerate)rR   ordneedrvniNwasr   revr  r   rF   rF   rG   _AOP_product	  s.   &

r  c                    s"  t  tr7|du rsd  S t fddt d D S |dk r'tdr2t | d |S t |S t  tr t }|du rasQtdd  t	 D S t fd	dt|d D S rkt
 t |S |d|d fv rw t S |d|fv rdS tt t	 | S t
t |S )
a  Return the number of combinations of ``n`` items taken ``k`` at a time.

    Possible values for ``n``:

        integer - set of length ``n``

        sequence - converted to a multiset internally

        multiset - {element: multiplicity}

    If ``k`` is None then the total of all combinations of length 0
    through the number of items represented in ``n`` will be returned.

    If ``replacement`` is True then a given item can appear more than once
    in the ``k`` items. (For example, for 'ab' sets of 2 would include 'aa',
    'ab', and 'bb'.) The multiplicity of elements in ``n`` is ignored when
    ``replacement`` is True but the total number of elements is considered
    since no element can appear more times than the number of elements in
    ``n``.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import nC
    >>> from sympy.utilities.iterables import multiset_combinations
    >>> nC(3, 2)
    3
    >>> nC('abc', 2)
    3
    >>> nC('aab', 2)
    2

    When ``replacement`` is True, each item can have multiplicity
    equal to the length represented by ``n``:

    >>> nC('aabc', replacement=True)
    35
    >>> [len(list(multiset_combinations('aaaabbbbcccc', i))) for i in range(5)]
    [1, 3, 6, 10, 15]
    >>> sum(_)
    35

    If there are ``k`` items with multiplicities ``m_1, m_2, ..., m_k``
    then the total of all combinations of length 0 through ``k`` is the
    product, ``(m_1 + 1)*(m_2 + 1)*...*(m_k + 1)``. When the multiplicity
    of each item is 1 (i.e., k unique items) then there are 2**k
    combinations. For example, if there are 4 unique items, the total number
    of combinations is 16:

    >>> sum(nC(4, i) for i in range(5))
    16

    See Also
    ========

    sympy.utilities.iterables.multiset_combinations

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Combination
    .. [2] https://tinyurl.com/cep849r

    Nr   c                 3   r  ra   nCr   r  rF   rG   r   
  r  znC.<locals>.<genexpr>rB   r   zk cannot be negativec                 s   s    | ]}|d  V  qdS r  rF   )r   r   rF   rF   rG   r   
  ro  c                 3   r  ra   r  r   r  rF   rG   r   
  r  )r  r   r{  rC   rq   r!   r  r  r   r  r  r  r  tupler  )rR   r   r  r  rF   r  rG   r  	  s0   
B 

 r  c                 C   s   | |  krdkrt jS  d| |fv rt jS | |krt jS || d kr(t| dS || d kr;d|  d t| d d S || d krKt| dt| d S t| |S )Nr   rB   r   r   r   )r   r   r   r!   
_stirling1rR   r   rF   rF   rG   _eval_stirling1
  s   

r  c                 C   sn   ddgdg|d   }t d| d D ]}t t||ddD ]}|d ||  ||d   ||< qqt|| S Nr   rB   r   re   rC   r  r   rR   r   rowr   r   rF   rF   rG   r  2
  s   "r  c                 C   s   | |  krdkrt jS  d| |fv rt jS | |krt jS || d kr(t| dS |dkr/t jS |dkr=td| d  d S t| |S )Nr   rB   r   )r   r   r   r!   r   
_stirling2r  rF   rF   rG   _eval_stirling2;
  s   

r  c                 C   sj   ddgdg|d   }t d| d D ]}t t||ddD ]}|||  ||d   ||< qqt|| S r  r  r  rF   rF   rG   r  N
  s   r  r   c                 C   s   t | } t |}| dk rtd|| krtjS |r&t| | d || d S |r4tj| |  t| | S |dkr=t| |S |dkrFt| |S td| )a
  Return Stirling number $S(n, k)$ of the first or second (default) kind.

    The sum of all Stirling numbers of the second kind for $k = 1$
    through $n$ is ``bell(n)``. The recurrence relationship for these numbers
    is:

    .. math :: {0 \brace 0} = 1; {n \brace 0} = {0 \brace k} = 0;

    .. math :: {{n+1} \brace k} = j {n \brace k} + {n \brace {k-1}}

    where $j$ is:
        $n$ for Stirling numbers of the first kind,
        $-n$ for signed Stirling numbers of the first kind,
        $k$ for Stirling numbers of the second kind.

    The first kind of Stirling number counts the number of permutations of
    ``n`` distinct items that have ``k`` cycles; the second kind counts the
    ways in which ``n`` distinct items can be partitioned into ``k`` parts.
    If ``d`` is given, the "reduced Stirling number of the second kind" is
    returned: $S^{d}(n, k) = S(n - d + 1, k - d + 1)$ with $n \ge k \ge d$.
    (This counts the ways to partition $n$ consecutive integers into $k$
    groups with no pairwise difference less than $d$. See example below.)

    To obtain the signed Stirling numbers of the first kind, use keyword
    ``signed=True``. Using this keyword automatically sets ``kind`` to 1.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import stirling, bell
    >>> from sympy.combinatorics import Permutation
    >>> from sympy.utilities.iterables import multiset_partitions, permutations

    First kind (unsigned by default):

    >>> [stirling(6, i, kind=1) for i in range(7)]
    [0, 120, 274, 225, 85, 15, 1]
    >>> perms = list(permutations(range(4)))
    >>> [sum(Permutation(p).cycles == i for p in perms) for i in range(5)]
    [0, 6, 11, 6, 1]
    >>> [stirling(4, i, kind=1) for i in range(5)]
    [0, 6, 11, 6, 1]

    First kind (signed):

    >>> [stirling(4, i, signed=True) for i in range(5)]
    [0, -6, 11, -6, 1]

    Second kind:

    >>> [stirling(10, i) for i in range(12)]
    [0, 1, 511, 9330, 34105, 42525, 22827, 5880, 750, 45, 1, 0]
    >>> sum(_) == bell(10)
    True
    >>> len(list(multiset_partitions(range(4), 2))) == stirling(4, 2)
    True

    Reduced second kind:

    >>> from sympy import subsets, oo
    >>> def delta(p):
    ...    if len(p) == 1:
    ...        return oo
    ...    return min(abs(i[0] - i[1]) for i in subsets(p, 2))
    >>> parts = multiset_partitions(range(5), 3)
    >>> d = 2
    >>> sum(1 for p in parts if all(delta(i) >= d for i in p))
    7
    >>> stirling(5, 3, 2)
    7

    See Also
    ========
    sympy.utilities.iterables.multiset_partitions


    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind
    .. [2] https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind

    r   zn must be nonnegativerB   r   zkind must be 1 or 2, not %s)r=   rq   r   r   r  rp   r  )rR   r   r  kindsignedrF   rF   rG   stirlingW
  s   V

r  c                 C   s   || ks|dk r
dS |d| fv rdS |dkrdS |dkr | d S | | }|dkr*|S d| | krIt |}|| dkrG|tt t|| 8 }|S dg| }td|d D ]}t|d |D ]}||  |||  7  < q^|d8 }qUdt|d| d  S )zxReturn the partitions of ``n`` items into ``k`` parts. This
    is used by ``nT`` for the case when ``n`` is an integer.r   rB   r   r   N)r.   r{  
fetch_itemslicerC   )rR   r   r  r  rU   r   r   rF   rF   rG   _nT
  s,   

r  c           	         s  t  tr!|du rt S t |tr!t  t|}tt |S t  tsRztt }|dkr9t	t |W S |t krCt
| t tyQ   t  Y nw  t }|du r`|dkr`dS |d|fv rhdS |dkst|dkr|du rt|d\}}t fddt
d|d D }|s|t |d 8 }|du r|d7 }|S | t kr|du rt|S t||S t }|du r| t S d}| t |d |D ]}|d7 }q|S )ap  Return the number of ``k``-sized partitions of ``n`` items.

    Possible values for ``n``:

        integer - ``n`` identical items

        sequence - converted to a multiset internally

        multiset - {element: multiplicity}

    Note: the convention for ``nT`` is different than that of ``nC`` and
    ``nP`` in that
    here an integer indicates ``n`` *identical* items instead of a set of
    length ``n``; this is in keeping with the ``partitions`` function which
    treats its integer-``n`` input like a list of ``n`` 1s. One can use
    ``range(n)`` for ``n`` to indicate ``n`` distinct items.

    If ``k`` is None then the total number of ways to partition the elements
    represented in ``n`` will be returned.

    Examples
    ========

    >>> from sympy.functions.combinatorial.numbers import nT

    Partitions of the given multiset:

    >>> [nT('aabbc', i) for i in range(1, 7)]
    [1, 8, 11, 5, 1, 0]
    >>> nT('aabbc') == sum(_)
    True

    >>> [nT("mississippi", i) for i in range(1, 12)]
    [1, 74, 609, 1521, 1768, 1224, 579, 197, 50, 9, 1]

    Partitions when all items are identical:

    >>> [nT(5, i) for i in range(1, 6)]
    [1, 2, 2, 1, 1]
    >>> nT('1'*5) == sum(_)
    True

    When all items are different:

    >>> [nT(range(5), i) for i in range(1, 6)]
    [1, 15, 25, 10, 1]
    >>> nT(range(5)) == sum(_)
    True

    Partitions of an integer expressed as a sum of positive integers:

    >>> from sympy import partition
    >>> partition(4)
    5
    >>> nT(4, 1) + nT(4, 2) + nT(4, 3) + nT(4, 4)
    5
    >>> nT('1'*4)
    5

    See Also
    ========
    sympy.utilities.iterables.partitions
    sympy.utilities.iterables.multiset_partitions
    sympy.functions.combinatorial.numbers.partition

    References
    ==========

    .. [1] https://web.archive.org/web/20210507012732/https://teaching.csse.uwa.edu.au/units/CITS7209/partition.pdf

    NrB   r   c                 3   s    | ]}t  |V  qd S ra   r  r   rQ   rF   rG   r   S  r   znT.<locals>.<genexpr>r   )r  r   rS  r=   r   r  r  r   r  nTrC   rU  r  r  divmodr{  r  r  r   r  r6   count_partitionsr  
enum_range)	rR   r   r  r  r   r   r  r  discardrF   rQ   rG   r  
  sT   
I

 

r  c                   @   s\   e Zd ZdZedd Zedd Zedd Zeee	j
e	j
gdd	 Zed
d ZdS )motzkina  
    The nth Motzkin number is the number
    of ways of drawing non-intersecting chords
    between n points on a circle (not necessarily touching
    every point by a chord). The Motzkin numbers are named
    after Theodore Motzkin and have diverse applications
    in geometry, combinatorics and number theory.

    Motzkin numbers are the integer sequence defined by the
    initial terms `M_0 = 1`, `M_1 = 1` and the two-term recurrence relation
    `M_n = rac{2*n + 1}{n + 2} * M_{n-1} + rac{3n - 3}{n + 2} * M_{n-2}`.


    Examples
    ========

    >>> from sympy import motzkin

    >>> motzkin.is_motzkin(5)
    False
    >>> motzkin.find_motzkin_numbers_in_range(2,300)
    [2, 4, 9, 21, 51, 127]
    >>> motzkin.find_motzkin_numbers_in_range(2,900)
    [2, 4, 9, 21, 51, 127, 323, 835]
    >>> motzkin.find_first_n_motzkins(10)
    [1, 1, 2, 4, 9, 21, 51, 127, 323, 835]


    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Motzkin_number
    .. [2] https://mathworld.wolfram.com/MotzkinNumber.html

    c                 C   s   zt | } W n
 ty   Y dS w | dkrM| dv rdS d}d}d}|| k rEd| d | d| d |  |d  }|d7 }|}|}|| k s%|| krKdS dS dS )NFr   )rB   r   TrB   r   r   )r=   rq   )rR   tn1tnr   rD   rF   rF   rG   
is_motzkin  s*   (zmotzkin.is_motzkinc                 C   s   d|   kr
|krYn tdg }| d  kr|kr"n n| d d}d}d}||krW|| kr5| | d| d | d| d |  |d  }|d7 }|}t|}||ks,|S td)Nr   rB   r   r   zEThe provided range is not valid. This condition should satisfy x <= y)appendro   rq   )rI   rZ   motzkinsr  r  r   rD   rF   rF   rG   find_motzkin_numbers_in_range  s$   

(z%motzkin.find_motzkin_numbers_in_rangec                 C   s   zt | } W n ty   tdw | dk rtddg}| dkr&|d d}d}d}|| krW|| d| d | d| d |  |d  }|d7 }|}t|}|| ks0|S )N.The provided number must be a positive integerr   rB   r   r   )r=   rq   r  ro   )rR   r  r  r  r   rD   rF   rF   rG   find_first_n_motzkins  s*   

(zmotzkin.find_first_n_motzkinsc                 C   s0   d|  d |d  d|  d |d   | d  S )Nr   rB   re   r   rd   rF   ri   rF   rF   rG   _motzkin  s   0zmotzkin._motzkinc                 C   sF   zt |}W n ty   tdw |dk rtdt| |d S )Nr  r   rB   )r=   rq   r   r  r   rF   rF   rG   rv     s   zmotzkin.evalN)r[   r\   r]   r^   r_   r  r  r  r<   r   r   r  r   rv   rF   rF   rF   rG   r  p  s    $


r  )rR   r   c                   s  ddl m} ddlm  ddlm dd | ||fddkr$td	| duryt| t	r1t
d
| s6tjS t| turEt| }t|}nt| tu rctfdd|  D  dd |  D }d}|shtjS t| }t| }t|}	no|dur| |stjS t|S |durt|trtfdd| D  dd | D }n&t|st|trt|}tfdd|D  tdd |D }nt
d|stjS tdd | D }t| }	d}tt|}
|
dkrt|	S t|}|
d |krtjS |
d |kr#|	dkr|dkrtjS |	d |
kr#t|
S |dk r-|du s0|rd|du rWg }d} | D ]\}}t|D ]}|| g|  | d7 } qEq=ttdd t |D S ddl!m"} tt#|| t$ fdd| D   dt%fS )a  return the number of derangements for: ``n`` unique items, ``i``
    items (as a sequence or multiset), or multiplicities, ``m`` given
    as a sequence or multiset.

    Examples
    ========

    >>> from sympy.utilities.iterables import generate_derangements as enum
    >>> from sympy.functions.combinatorial.numbers import nD

    A derangement ``d`` of sequence ``s`` has all ``d[i] != s[i]``:

    >>> set([''.join(i) for i in enum('abc')])
    {'bca', 'cab'}
    >>> nD('abc')
    2

    Input as iterable or dictionary (multiset form) is accepted:

    >>> assert nD([1, 2, 2, 3, 3, 3]) == nD({1: 1, 2: 2, 3: 3})

    By default, a brute-force enumeration and count of multiset permutations
    is only done if there are fewer than 9 elements. There may be cases when
    there is high multiplicity with few unique elements that will benefit
    from a brute-force enumeration, too. For this reason, the `brute`
    keyword (default None) is provided. When False, the brute-force
    enumeration will never be used. When True, it will always be used.

    >>> nD('1111222233', brute=True)
    44

    For convenience, one may specify ``n`` distinct items using the
    ``n`` keyword:

    >>> assert nD(n=3) == nD('abc') == 2

    Since the number of derangments depends on the multiplicity of the
    elements and not the elements themselves, it may be more convenient
    to give a list or multiset of multiplicities using keyword ``m``:

    >>> assert nD('abc') == nD(m=(1,1,1)) == nD(m={1:3}) == 2

    r   )	integrate)laguerrerI   c                 S   s&   t | ts	td| dk rtddS )Nzexpecting integer valuesr   zvalue must not be negativeT)r  r   rU  rq   r  rF   rF   rG   ok  s
   
znD.<locals>.okNr   zenter only 1 of i, n, or mz"items must be a list or dictionaryc                 3       | ]} |V  qd S ra   rF   rm  r  rF   rG   r   .  ro  znD.<locals>.<genexpr>c                 S   s   i | ]	\}}|r||qS rF   rF   r   r   rq  rF   rF   rG   
<dictcomp>/  r   znD.<locals>.<dictcomp>c                 3   s$    | ]\}} |o |V  qd S ra   rF   )r   r   r   r  rF   rG   r   =  s   " c                 S   s   i | ]\}}|| r||qS rF   rF   r  rF   rF   rG   r  >  s    c                 3   r  ra   rF   r   r  rF   rG   r   A  ro  c                 S   s   g | ]}|r|qS rF   rF   r   rF   rF   rG   r   B  r\  znD.<locals>.<listcomp>zexpecting iterablec                 s   s    | ]	\}}|| V  qd S ra   rF   r  rF   rF   rG   r   G  r  rB   r   c                 s   s    | ]}d V  qdS r  rF   r   rF   rF   rG   r   ^  s    )expc                    s   g | ]\}} || qS rF   rF   )r   r   r   )r  rI   rF   rG   r   `  s    )&sympy.integrals.integralsr  #sympy.functions.special.polynomialsr  	sympy.abcrI   countrq   r  r   rU  r   r   typer  r  r9   r   r_  r`  r{  r   r#   r;   strro   maxr   r"   rC   r  r   r:   r  r  rJ  r   r   )r   bruterR   r   r  r   msr  countsnkeybignvalrq  r   r  rF   )r  r  rI   rG   nD  s   ,




r  )NF)Nr   Fra   r   )r^   mathr   collectionsr   typingr   r   
sympy.corer   r   r   r   sympy.core.cacher	   sympy.core.containersr
   sympy.core.exprr   sympy.core.functionr   r   r   sympy.core.logicr   sympy.core.mulr   sympy.core.numbersr   r   r   r   r   r   sympy.core.relationalr   r   r   r   sympy.external.gmpyr   r   r   r   r   r    (sympy.functions.combinatorial.factorialsr!   r"   r#   r  r%   $sympy.functions.elementary.piecewiser&   sympy.ntheory.factor_r'   r(   r)   r*   r+   sympy.ntheory.generater,   sympy.ntheory.partitions_r-   r.   sympy.ntheory.primetestr/   r0   sympy.polys.appellseqsr1   r2   r3   sympy.polys.polytoolsr5   sympy.utilities.enumerativer6   sympy.utilities.exceptionsr8   sympy.utilities.iterablesr9   r:   r;   sympy.utilities.memoizationr<   sympy.utilities.miscr=   r  r>   r?   mpmath.libmpr@   rb   rH   rg   rJ   r`   r   r   r   r   r   r  r%  r"  rH  rS  rW  rc  rf  ri  rj  rk  rw  rz  r}  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rF   rF   rF   rG   <module>   s      	 X4Z ?      s3CH0G'P452:?

B4

3^


l

+ }