a
    RG5d                    @   s  d 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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 dd
lmZ ddlmZ ddlmZmZm Z m!Z!m"Z" ddl#m$Z$m%Z% ddl&m'Z' ddl(m)Z)m*Z*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<Z<m=Z= ddl>m?Z@ dd ZAedZBdd ZCG dd deZDG dd  d eZEG d!d" d"eZFG d#d$ d$eZGG d%d& d&eZHG d'd( d(eZIG d)d* d*eZJG d+d, d,eZKG d-d. d.eZLG d/d0 d0eZMd1d1gZNG d2d3 d3eZOG d4d5 d5ePZQd6ZRd7ZSeTd8eSZUd9d: ZVdXd<d=ZWedYd>d?ZXed@dA ZYdZdBdCZZdDdE Z[edFdG Z\dHdI Z]edJdK Z^d[dMdNZ_edOdP Z`d\dQdRZaG dSdT dTeZbd]d8d8dUdVdWZcd8S )^a6  
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)CallableDictTuple)SSymbolAddDummy)cacheit)pure_complex)Expr)Function
expand_mul)	fuzzy_not)Mul)EpiooRationalInteger)is_leis_gt)
SYMPY_INTS)binomial	factorialsubfactorial)isprime	is_square)MultisetPartitionTraversersympy_deprecation_warning)multisetmultiset_derangementsiterable)recurrence_memo)as_int)bernfracworkprec)ifibc                 C   s   t t| |d S N   )r   range)ab r/   a/var/www/html/django/DPS/env/lib/python3.9/site-packages/sympy/functions/combinatorial/numbers.py_product$   s    r1   xc                 C   s   ||  dkS )Nr   r/   pnr/   r/   r0   _divides2   s    r6   c                   @   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 )
carmichaela0  
    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 import carmichael
    >>> carmichael.find_first_n_carmichaels(5)
    [561, 1105, 1729, 2465, 2821]
    >>> carmichael.find_carmichael_numbers_in_range(0, 562)
    [561]
    >>> carmichael.find_carmichael_numbers_in_range(0,1000)
    [561]
    >>> carmichael.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   s   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)r!   r   r5   r/   r/   r0   is_perfect_squareh   s    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.
        r8   r9   r:   r   r    r3   r/   r/   r0   dividest   s    zcarmichael.dividesc                 C   s   t dddd t| S )Nzi
is_prime is just a wrapper around sympy.ntheory.primetest.isprime so use that
directly instead.
        r8   r9   r:   )r!   r   r=   r/   r/   r0   is_prime   s    zcarmichael.is_primec                    s    dkr dks$t  s$ d dkr(dS d g}| fddtd d d dD  |D ]:}t|rv|dkrv dS t |r\t|d  d s\ dS q\dS td	d S )
Nr   r+      Fc                    s   g | ]} | d kr|qS r   r/   .0ir=   r/   r0   
<listcomp>       z,carmichael.is_carmichael.<locals>.<listcomp>   Tz6The provided number must be greater than or equal to 0)r   extendr,   r   r6   
ValueError)r5   divisorsrE   r/   r=   r0   is_carmichael   s    (zcarmichael.is_carmichaelc                 C   sb   d|   kr|krVn n>| d dkr>dd t | d |dD S dd t | |dD S ntdd S )Nr   rA   c                 S   s   g | ]}t |r|qS r/   r7   rL   rC   r/   r/   r0   rF      rG   z?carmichael.find_carmichael_numbers_in_range.<locals>.<listcomp>r+   c                 S   s   g | ]}t |r|qS r/   rM   rC   r/   r/   r0   rF      rG   zQThe provided range is not valid. x and y must be non-negative integers and x <= y)r,   rJ   )r2   yr/   r/   r0    find_carmichael_numbers_in_range   s
    z+carmichael.find_carmichael_numbers_in_rangec                 C   s8   d}t  }t|| k r4t|r*|| |d7 }q
|S Nr+   rA   )listlenr7   rL   append)r5   rE   Zcarmichaelsr/   r/   r0   find_first_n_carmichaels   s    


z#carmichael.find_first_n_carmichaelsN)__name__
__module____qualname____doc__staticmethodr>   r?   r@   rL   rO   rT   r/   r/   r/   r0   r7   5   s   2






r7   c                   @   sV   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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] http://mathworld.wolfram.com/FibonacciNumber.html

    c                 C   s   t | S N)_ifibr=   r/   r/   r0   _fib   s    zfibonacci._fibNc                 C   s   |d t |d    S )N_symexpandr5   prevr/   r/   r0   _fibpoly   s    zfibonacci._fibpolyc                 C   s|   |t ju rt jS |jrx|d u rVt|}|dk rFt j|d  t|  S t| |S n"|dk rftd| 	|
t|S d S )Nr   r+   zDFibonacci polynomials are defined only for positive integer indices.)r   Infinity
is_IntegerintNegativeOnerZ   r   r]   rJ   re   subsra   clsr5   symr/   r/   r0   eval   s    
zfibonacci.evalc                 K   sD   ddl m} d|  |d d|d | |d d |   d S )Nr   sqrtrA      r+   (sympy.functions.elementary.miscellaneousrp   selfr5   kwargsrp   r/   r/   r0   _eval_rewrite_as_sqrt  s    zfibonacci._eval_rewrite_as_sqrtc                 K   s(   t j| dt j |   dt j d  S rP   )r   GoldenRatioru   r5   rv   r/   r/   r0   _eval_rewrite_as_GoldenRatio
  s    z&fibonacci._eval_rewrite_as_GoldenRatio)N)rU   rV   rW   rX   rY   r]   r%   r   Onera   re   classmethodrn   rw   rz   r/   r/   r/   r0   rZ      s   )
rZ   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] http://mathworld.wolfram.com/LucasNumber.html

    c                 C   s2   |t ju rt jS |jr.t|d t|d  S d S r*   )r   rf   rg   rZ   rl   r5   r/   r/   r0   rn   5  s    
z
lucas.evalc                 K   s8   ddl m} d|  d|d | |d d |   S )Nr   ro   rA   r+   rq   rr   rt   r/   r/   r0   rw   =  s    zlucas._eval_rewrite_as_sqrtN)rU   rV   rW   rX   r|   rn   rw   r/   r/   r/   r0   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] http://mathworld.wolfram.com/TribonacciNumber.html
    .. [3] https://oeis.org/A000073

    c                 C   s   |d |d  |d  S )Nr^   r_   r/   rc   r/   r/   r0   _tribp  s    ztribonacci._tribrA   c                 C   s(   |d t |d   t d |d    S )Nr   r^   rA   r_   r`   rc   r/   r/   r0   	_tribpolyu  s    ztribonacci._tribpolyNc                 C   sZ   |t ju rt jS |jrVt|}|dk r.td|d u rDt| |S | |t	|S d S )Nr   zITribonacci polynomials are defined only for non-negative integer indices.)
r   rf   rg   rh   rJ   r   r   r   rj   ra   rk   r/   r/   r0   rn   z  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   cbrtrp   r_   rH   rA   r+      !   )rs   r   rp   r   ImaginaryUnit)
ru   r5   rv   r   rp   wr-   r.   cTnr/   r/   r0   rw     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   rH   rA      )#sympy.functions.elementary.integersr   rs   r   rp   r   TribonacciConstantHalf)ru   r5   rv   r   r   rp   r.   r   r/   r/   r0   #_eval_rewrite_as_TribonacciConstant  s
    &z.tribonacci._eval_rewrite_as_TribonacciConstant)N)rU   rV   rW   rX   rY   r%   r   Zeror{   r   ra   r   r|   rn   rw   r   r/   r/   r/   r0   r   I  s   &r   c                   @   s^   e Zd ZU dZee ed< edd Ze	j
eddeddd	Zd
ddd	ZedddZdS )	bernoulliaI  
    Bernoulli numbers / Bernoulli polynomials

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

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

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

    The Bernoulli polynomials satisfy the analogous formula:

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

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

    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 2/3 of the terms. For Bernoulli polynomials, we use the
    formula in the definition.

    * ``bernoulli(n)`` gives the nth Bernoulli number, `B_n`
    * ``bernoulli(n, x)`` gives the nth Bernoulli polynomial in `x`, `B_n(x)`

    Examples
    ========

    >>> from sympy import bernoulli

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

    See Also
    ========

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

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Bernoulli_number
    .. [2] https://en.wikipedia.org/wiki/Bernoulli_polynomial
    .. [3] http://mathworld.wolfram.com/BernoulliNumber.html
    .. [4] http://mathworld.wolfram.com/BernoulliPolynomial.html

    argsc                 C   s   d}t t| d | d }td| d d D ]`}||t| d|   7 }|t| d d|  d | d|  9 }|td| d d| d  }q,| d dkrt| d d | }nt| d d| }|t| d |  S )Nr   rH      r+   r   	   )rh   r   r,   r   r1   r   )r5   sr-   jr/   r/   r0   _calc_bernoulli  s    & zbernoulli._calc_bernoullir+   r   r_      )r   rA   r   r   rA   r   Nc           
         sN  j r&jrjrjr$tjS tju rLd u r@tddS tj S nЈd u rjr`tj	S t
dkrt\}}tt
|t
|S d } j| }|kr j S t|d d dD ]"} |}| j|< | j|< q|S t
 fddtd D }	t|	 S ntdd u rJjrJd jrJtj	S d S )	Nr_   rA   i  r   c                    s*   g | ]"}t | | |   qS r/   r   rD   krk   r/   r0   rF     rG   z"bernoulli.eval.<locals>.<listcomp>r+   zCBernoulli numbers are defined only for nonnegative integer indices.)	is_Numberrg   is_nonnegativeis_zeror   r{   r   r   is_oddr   rh   r'   _highest_cacher,   r   r	   rJ   is_positive)
rl   r5   rm   r4   qcaseZhighest_cachedrE   r.   resultr/   rk   r0   rn     s>    







zbernoulli.eval)N)rU   rV   rW   rX   tTupler   __annotations__rY   r   r   r{   r   r   r   r|   rn   r/   r/   r/   r0   r     s   
A
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 )bellax  
    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] http://mathworld.wolfram.com/BellNumber.html
    .. [3] http://mathworld.wolfram.com/BellPolynomial.html

    r+   c                 C   s<   d}d}t d| D ]$}|| |  | }||||  7 }q|S r*   )r,   r5   rd   r   r-   r   r/   r/   r0   _bellr  s    z
bell._bellc                 C   sT   d}d}t d| d D ]0}|| | d  |d  }||||d   7 }qtt| S rP   )r,   r   ra   r   r/   r/   r0   
_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 }|| |  | }qJt|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   r+   rA   )r   r{   r   r,   r   _bell_incomplete_polyr   )r5   r   symbolsr   r-   mr/   r/   r0   r     s    
zbell._bell_incomplete_polyNc                 C   s   |t ju r |d u rt jS td|js0|jdu r8td|jr|jr|d u r^t| t	|S |d u r|| 
t	|t|S | t	|t	||}|S d S )NzBell polynomial is not definedFza non-negative integer expected)r   rf   rJ   is_negative
is_integerrg   r   r   r   rh   r   rj   ra   r   )rl   r5   k_symr   rr/   r/   r0   rn     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nonnegativer+   )sympy.concrete.summationsr   r   r
   r   r   r   rf   )ru   r5   r   r   rv   r   r   r/   r/   r0   _eval_rewrite_as_Sum  s    zbell._eval_rewrite_as_Sum)NN)NN)rU   rV   rW   rX   rY   r%   r   r   r{   ra   r   r   r|   rn   r   r/   r/   r/   r0   r   1  s   @

r   c                   @   sd   e Zd ZdZi ZedddZdddZddd	Zdd
dZ	dddZ
dd ZdddZ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)``

    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")

    >>> 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 - polygamma(2, 1)/2

    >>> harmonic(n,m).rewrite(polygamma)
    (-1)**m*(polygamma(m - 1, 1) - polygamma(m - 1, n + 1))/factorial(m - 1)

    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)
    -polygamma(2, 1)/2

    However we cannot compute the general relation yet:

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

    which equals ``zeta(m)`` for ``m > 1``.

    See Also
    ========

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

    References
    ==========

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

    Nc                    s   ddl m}  tju r| |S  d u r,tj  jr6|S |tju rv jrLtjS t tjr^tjS t	 tjrr| S d S |dkrtj
S |jr|jr҈ jr҈ | jvrtdg fdd}|| j < | j  t|S d S )Nr   )zetac                    s   |d t j|     S )Nr_   r   r{   rc   r   r/   r0   ff  s    zharmonic.eval.<locals>.f)&sympy.functions.special.zeta_functionsr   r   r{   r   rf   r   NaNr   r   r   rg   r   
_functionsr%   rh   )rl   r5   r   r   r   r/   r   r0   rn   L  s.    



zharmonic.evalr+   c                 K   sB   ddl m} tj| t|d  ||d d||d |d   S )Nr   	polygammar+   )'sympy.functions.special.gamma_functionsr   r   ri   r   ru   r5   r   rv   r   r/   r/   r0   _eval_rewrite_as_polygammal  s    z#harmonic._eval_rewrite_as_polygammac                 K   s   ddl m} | |S Nr   r   r   r   rewriter   r/   r/   r0   _eval_rewrite_as_digammap  s    z!harmonic._eval_rewrite_as_digammac                 K   s   ddl m} | |S r   r   r   r/   r/   r0   _eval_rewrite_as_trigammat  s    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   r+   )r   r   r
   r   r{   )ru   r5   r   rv   r   r   r/   r/   r0   r   x  s
    zharmonic._eval_rewrite_as_Sumc              	      s  ddl m} | jd }t| jdkr.| jd nd}|tjkr|jr|jd }||  |jr|jr fddt	|ddD t
 g }t| S |jr|jrƇ 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   rA   r+   c                    s   g | ]}t j |  qS r/   r   rC   nnewr/   r0   rF     rG   z.harmonic._eval_expand_func.<locals>.<listcomp>r_   c                    s   g | ]}t j  |  qS r/   r   rC   r   r/   r0   rF     rG   logr   )sincoscotr   )r   r   r   rR   r   r{   is_Addrg   r   r,   r   r	   r   is_Rationalas_numer_denomr   &sympy.functions.elementary.exponentialr   r   r   (sympy.functions.elementary.trigonometricr   r   r   r
   r   )ru   hintsr   r5   r   offr   r4   r   ur   r   r   r   r   r   t1t2t3r/   r   r0   _eval_expand_func  s>    

$$" $zharmonic._eval_expand_funcc                 K   s    ddl m} | |jdddS )Nr   r   	tractableT)deepr   )ru   r5   r   limitvarrv   r   r/   r/   r0   _eval_rewrite_as_tractable  s    z#harmonic._eval_rewrite_as_tractablec                 C   s4   ddl m} tdd | jD r0| ||S d S )Nr   r   c                 s   s   | ]}|j V  qd S r[   )	is_numberrC   r/   r/   r0   	<genexpr>  rG   z'harmonic._eval_evalf.<locals>.<genexpr>)r   r   allr   r   _eval_evalf)ru   precr   r/   r/   r0   r     s    zharmonic._eval_evalf)N)r+   )r+   )r+   )N)r+   N)rU   rV   rW   rX   r   r|   rn   r   r   r   r   r   r   r   r/   r/   r/   r0   r     s   



$
r   c                   @   s0   e Zd ZdZed	ddZd
ddZdd ZdS )eulera  
    Euler numbers / Euler polynomials

    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 [5]_

    .. math:: E_n(x) = \sum_{k=0}^n \binom{n}{k} \frac{E_k}{2^k}
                       \left(x - \frac{1}{2}\right)^{n-k}.

    However, numerical evaluation of the Euler polynomial is computed
    more efficiently (and more accurately) using the mpmath library.

    * ``euler(n)`` gives the `n^{th}` Euler number, `E_n`.
    * ``euler(n, x)`` gives the `n^{th}` Euler polynomial, `E_n(x)`.

    Examples
    ========

    >>> from sympy import euler, Symbol, S
    >>> [euler(n) for n in range(10)]
    [1, 0, -1, 0, 5, 0, -61, 0, 1385, 0]
    >>> 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
    ========

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

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Euler_numbers
    .. [2] http://mathworld.wolfram.com/EulerNumber.html
    .. [3] https://en.wikipedia.org/wiki/Alternating_permutation
    .. [4] http://mathworld.wolfram.com/AlternatingPermutation.html
    .. [5] http://dlmf.nist.gov/24.2#ii

    Nc                    sT  j r0jr(jr(d u rZjr,tjS ddlm} |j	|j
dd}t|S tdd}|rtdd |D rtdd |D rddlm} ttd	d
 |D }t| |}W d    n1 s0    Y  t||S t fdd
td D }t|  S ntdd u rPjrPjrPtjS d S )Nr   mpT)exact)or_realc                 s   s   | ]}|j p|jV  qd S r[   )is_Floatrg   rD   r-   r/   r/   r0   r     rG   zeuler.eval.<locals>.<genexpr>c                 s   s   | ]}|j V  qd S r[   )r   r   r/   r/   r0   r     rG   c                 S   s   g | ]}|j r|jqS r/   )r   _precr   r/   r/   r0   rF     rG   zeuler.eval.<locals>.<listcomp>c                    s8   g | ]0}t | | d |  tj |   qS )rA   )r   r   r   r   rl   r   rm   r/   r0   rF     rG   r+   z?Euler numbers are defined only for nonnegative integer indices.)r   rg   r   r   r   r   mpmathr   
_to_mpmathr   eulernumr   r   r   anyrh   minr(   	eulerpolyr   _from_mpmathr,   r	   rb   rJ   r   )rl   r   rm   r   resZreimr   r   r/   r   r0   rn     s4    
*
z
euler.evalc                 K   s   ddl m} |d u r|jrt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 |rtddd}|t||t| d|  |tj	 ||   |d|fS d S )	Nr   r   r   Tr   r   rA   r+   )
r   r   is_evenr
   r   r   r   ri   r   r   )ru   r5   r2   rv   r   r   r   ZEmr/   r/   r0   r      s$    zeuler._eval_rewrite_as_Sumc                 C   s  t | jdkr| jd d fn| j\}}|d u r|jr|jrddlm} ||}t| ||}W d    n1 sx0    Y  t	
||S |r
|jr
|jr
|jr
ddlm} t|}||}t| |||}W d    n1 s0    Y  t	
||S d S )Nr+   r   r   )rR   r   rg   r   r   r   r   r(   r   r   r   r   rh   r   )ru   r   r   r2   r   r   r/   r/   r0   r   .  s    &

(

*zeuler._eval_evalf)N)N)rU   rV   rW   rX   r|   rn   r   r   r/   r/   r/   r0   r     s
   G#
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 )catalana;  
    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((1 - n, -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
    ========

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

    References
    ==========

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

    c                 C   s   ddl m} |jr|js$|jrP|jrPd| ||tj  |tj||d   S |jr|jr|d jrltj	S |d j
rtddS d S )Nr   gammar   rA   r+   r_   )r   r   rg   r   is_nonintegerr   r   r   r   r   r   r   )rl   r5   r   r/   r/   r0   rn     s    ,

zcatalan.evalr+   c                 C   sP   ddl m} ddlm} | jd }t||d|tj |d|d  |d  S )Nr   r   r   rA   r   )r   r   r   r   r   r   r   r   )ru   argindexr   r   r5   r/   r/   r0   fdiff  s    
zcatalan.fdiffc                 K   s   t d| ||d  S NrA   r+   r   ry   r/   r/   r0   _eval_rewrite_as_binomial  s    z!catalan._eval_rewrite_as_binomialc                 K   s    t d| t |d t |  S r  r   ry   r/   r/   r0   _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   rA   )r   r   r   r   )ru   r5   	piecewiserv   r   r/   r/   r0   _eval_rewrite_as_gamma  s    zcatalan._eval_rewrite_as_gammac                 K   s$   ddl m} |d| | gdgdS )Nr   )hyperr+   rA   )sympy.functions.special.hyperr	  )ru   r5   rv   r	  r/   r/   r0   _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   positiverA   )sympy.concrete.productsr  r   r   r
   )ru   r5   rv   r  r   r/   r/   r0   _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 Nr   T)r   r   r   ru   r/   r/   r0   _eval_is_integer  s    zcatalan._eval_is_integerc                 C   s   | j d jrdS d S r  )r   r   r  r/   r/   r0   _eval_is_positive  s    zcatalan._eval_is_positivec                 C   s$   | j d jr | j d d jr dS d S )Nr   rH   Tr   r   r   r  r/   r/   r0   _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   )ru   r   r   r/   r/   r0   r     s    zcatalan._eval_evalfN)r+   )T)rU   rV   rW   rX   r|   rn   r  r  r  r  r  r  r  r  r  r   r/   r/   r/   r0   r   F  s   O


r   c                   @   sT   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d Zdd ZdS )genocchia  
    Genocchi numbers

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

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

    Examples
    ========

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

    See Also
    ========

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

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Genocchi_number
    .. [2] http://mathworld.wolfram.com/GenocchiNumber.html

    c                 C   s`   |j r6|jr|jrtdddtd|   t| S |jrL|d jrLtjS |d j	r\tj
S d S )Nz7Genocchi numbers are defined only for positive integersrA   r+   )r   rg   is_nonpositiverJ   r   r   r   r   r   r   r{   r~   r/   r/   r0   rn     s    
zgenocchi.evalc                 K   s,   |j r(|jr(dtd|  t| d S d S rP   )r   r   r   r   ry   r/   r/   r0   _eval_rewrite_as_bernoulli  s    z#genocchi._eval_rewrite_as_bernoullic                 C   s    | j d jr| j d jrdS d S r  r  r  r/   r/   r0   r    s    zgenocchi._eval_is_integerc                 C   s.   | j d }|jr*|jr*|jr dS |d jS d S )Nr   FrA   )r   r   r   r   ru   r5   r/   r/   r0   _eval_is_negative  s
    
zgenocchi._eval_is_negativec                 C   s8   | j d }|jr4|jr4|jr*t|d jS |d jS d S Nr   r+   rA   )r   r   r   r   r   r   r  r/   r/   r0   r    s
    
zgenocchi._eval_is_positivec                 C   s.   | j d }|jr*|jr*|jr dS |d jS d S )Nr   Fr+   )r   r   r   r   r  r/   r/   r0   _eval_is_even  s
    
zgenocchi._eval_is_evenc                 C   s2   | j d }|jr.|jr.|jr dS t|d jS d S )Nr   Tr+   )r   r   r   r   r   r  r/   r/   r0   _eval_is_odd$  s
    
zgenocchi._eval_is_oddc                 C   s   | j d }|d jS )Nr      )r   r   r  r/   r/   r0   _eval_is_prime+  s    
zgenocchi._eval_is_primeN)rU   rV   rW   rX   r|   rn   r  r  r  r  r  r  r  r/   r/   r/   r0   r    s   
r  r+   c                   @   s@   e Zd ZdZedd Zedd Zdd Z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

    c                 C   s   t t}| |k rt|  S t|| d D ]}d\}}}d}|d| d 7 }||kr`|t||  7 }|d7 }|| }||kr|t||  7 }|dkrqq4||d dkr|n| 7 }q4t| q&|S )Nr+   )r   r   r   r   rH   rA   )rR   _npartitionr,   rS   )r5   L_nvr4   rE   r   gpr/   r/   r0   
_partition[  s$    
zpartition._partitionc                 C   sV   |j }|dkrtdn:|rR|jr(tjS |js8|d jr>tjS |jrRt| 	|S d S )NFz/Partition numbers are defined only for integersr+   )
r   rJ   r   r   r   r   r{   rg   r   r&  )rl   r5   is_intr/   r/   r0   rn   s  s    
zpartition.evalc                 C   s   | j d jrdS d S r  r   r   r  r/   r/   r0   r    s    zpartition._eval_is_integerc                 C   s   | j d jrdS d S )Nr   Fr(  r  r/   r/   r0   r    s    zpartition._eval_is_negativec                 C   s   | j d }|jr|jrdS d S r  )r   r   r   r  r/   r/   r0   r    s    
zpartition._eval_is_positiveN)rU   rV   rW   rX   rY   r&  r|   rn   r  r  r  r/   r/   r/   r0   r   :  s    

r   c                   @   s   e Zd ZdS )_MultisetHistogramN)rU   rV   rW   r/   r/   r/   r0   r)    s   r)  r_   r^   Nc           	         s   t  trdtdd   D s$tt  }t fdd D }t fdd D ||g S t  t }t	|}t	 }||krdg| ||g  t S tt
|t|}tt
t|d| } D ]}|||   d7  < qt|S d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)
isinstancerh   )rD   r$  r/   r/   r0   r     rG   z&_multiset_histogram.<locals>.<genexpr>c                 3   s   | ]} | d krdV  qdS )r   r+   Nr/   r   r=   r/   r0   r     rG   c                    s    g | ]} | d kr | qS rB   r/   r   r=   r/   r0   rF     rG   z'_multiset_histogram.<locals>.<listcomp>r+   rB   N)r*  dictr   valuesrJ   sumr)  rQ   setrR   zipr,   _multiset_histogram)	r5   totitemsr   lenslennr   drE   r/   r=   r0   r0    s$    
r0  Fc                 C   sD   zt | } W n& ty2   ttt| || Y S 0 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&   rJ   r   _nPr0  )r5   r   replacementr/   r/   r0   nP  s
    ;r8  c                    s  |dkrdS t  tr|d u r>t fddt d D S rJ | S | krVdS | krft|S |dkrr S t | d  S nzt  tr|d u rt fddt t d D S rЈ t | S | t k rt|t	dd  t
 D  S | t krdS |dkr  t S d}t  tt t
 D ]} | sNq< t  d8  <  | dkrd |<  t  d8  < |tt |d 7 } t  d7  < d |< n6 |  d8  < |tt |d 7 } |  d7  <  t  d7  < q<|S d S )Nr   r+   c                 3   s   | ]}t  |V  qd S r[   r6  rC   r5   r7  r/   r0   r   	  rG   z_nP.<locals>.<genexpr>c                 3   s   | ]}t  |V  qd S r[   r9  rC   r:  r/   r0   r     rG   c                 S   s   g | ]}|d krt |qS )r+   r  rC   r/   r/   r0   rF     rG   z_nP.<locals>.<listcomp>)r*  r   r-  r,   r   r1   r)  _N_ITEMSr   _MrQ   rR   r6  )r5   r   r7  r1  rE   r/   r:  r0   r6    sT    
 $


r6  c                 C   s*  t | } t| }|d d }dg|  d  }|d|t|   |d| }| r|  }|d }|dd }tdt|t|D ]}||  ||d  7  < qt||D ](}||  ||d  |||   7  < qqPt 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
    http://tinyurl.com/cep849r, but in a refactored form.

    rA   r+   rB   Nr_   )rQ   r-  poprI   rR   r,   r   reversedr   rh   	enumerate)r5   ordneedrvniNwasrE   revr5  r   r/   r/   r0   _AOP_product6  s,    (
rH  c                    s*  t  trn|du r>sd  S t fddt d D S |dk rNtdrdt | d |S t |S t  tr t }|du rĈstdd  t	 D S t fd	dt|d D S rt
 t |S |d|d fv r t S |d|fv rdS tt t	 | S t
t |S d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] http://tinyurl.com/cep849r

    NrA   c                 3   s   | ]}t  |V  qd S r[   nCrC   r:  r/   r0   r     rG   znC.<locals>.<genexpr>r+   r   zk cannot be negativec                 s   s   | ]}|d  V  qdS r+   Nr/   )rD   r   r/   r/   r0   r     rG   c                 3   s   | ]}t  |V  qd S r[   rI  rC   r:  r/   r0   r     rG   )r*  r   r-  r,   rJ   r   r)  r;  r   r=  rJ  r<  rH  tupler0  )r5   r   r7  rE  r/   r:  r0   rJ  j  s0    B
 
 rJ  c                 C   s   | |  krdkrn nt jS d| |fv r0t jS | |kr>t jS || d krTt| dS || d krzd|  d t| d d S || d krt| dt| d S t| |S )Nr   r+   rA   rH   r   )r   r{   r   r   
_stirling1r5   r   r/   r/   r0   _eval_stirling1  s    
rO  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   r+   rA   r_   r,   r   r   r5   r   rowrE   r   r/   r/   r0   rM    s
    $rM  c                 C   s   | |  krdkrn nt jS d| |fv r0t jS | |kr>t jS || d krTt| dS |dkrbt jS |dkr~td| d  d S t| |S r  )r   r{   r   r   r   
_stirling2rN  r/   r/   r0   _eval_stirling2  s    
rU  c                 C   sj   ddgdg|d   }t d| d D ]8}t t||ddD ] }|||  ||d   ||< q:q$t|| S rP  rQ  rR  r/   r/   r0   rT    s
     rT  rA   c                 C   s   t | } t |}| dk r td|| kr.tjS |rLt| | d || d S |rhtj| |  t| | S |dkrzt| |S |dkrt| |S td| dS )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 nonnegativer+   rA   zkind must be 1 or 2, not %sN)r&   rJ   r   r   rU  ri   rO  )r5   r   r5  kindsignedr/   r/   r0   stirling   s    V

rX  c                 C   s   || ks|dk rdS |d| fv r$dS |dkr0dS |dkr@| d S | | }|dkrT|S d| | krt |}|| dkr|ttd||  8 }|S dg| }td|d D ]8}t|d |D ]}||  |||  7  < q|d8 }qd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   r+   rA   rH   N)r   r&  r-  r!  r,   )r5   r   r5  r1  r4   rE   r   r/   r/   r0   _nTl  s,    


rY  c           	         s  t  trB|du rt S t |trBt  t|}tt |S t  tsz@tt }|dkrrt	t |W S |t krt
| tW n ty   t  Y n0  t }|du r|dkrdS |d|fv rdS |dks|dkrL|du rLt|d\}}t fddt
d|d D }|s6|t |d 8 }|du rH|d7 }|S | t krv|du rlt|S t||S t }|du r| t S d}| t |d |D ]}|d7 }q|S )aI  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] http://undergraduate.csse.uwa.edu.au/units/CITS7209/partition.pdf

    Nr+   rA   c                 3   s   | ]}t  |V  qd S r[   rI  rC   r=   r/   r0   r     rG   znT.<locals>.<genexpr>r   )r*  r   r   r&   r   rY  r)  rR   r.  nTr,   	TypeErrorr0  r;  divmodr-  rJ  r<  r   rX  r   count_partitionsr=  
enum_range)	r5   r   r   rE  r   r   rC  r1  discardr/   r=   r0   rZ    sR    I


 



rZ  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 0 | dkr| dv r6dS d}d}d}|| k rd| d | d| d |  |d  }|d7 }|}|}qB|| krdS dS ndS d S )NFr   )r+   rA   Tr+   rA   rH   )r&   rJ   )r5   tn1tnrE   r-   r/   r/   r0   
is_motzkin>  s&    (zmotzkin.is_motzkinc                 C   s   d|   kr|krn nt  }| d  kr2|kr@n n
|d d}d}d}||kr|| krf|| d| d | d| d |  |d  }|d7 }|}t|}qL|S tdd S )Nr   r+   rA   rH   zEThe provided range is not valid. This condition should satisfy x <= y)rQ   rS   rh   rJ   )r2   rN   motzkinsra  rb  rE   r-   r/   r/   r0   find_motzkin_numbers_in_rangeY  s     

(
z%motzkin.find_motzkin_numbers_in_rangec                 C   s   zt | } W n ty&   tdY n0 | dk r8tddg}| dkrP|d d}d}d}|| kr|| d| d | d| d |  |d  }|d7 }|}t|}q\|S )N.The provided number must be a positive integerr   r+   rA   rH   )r&   rJ   rS   rh   )r5   rd  ra  rb  rE   r-   r/   r/   r0   find_first_n_motzkinso  s&    

(
zmotzkin.find_first_n_motzkinsc                 C   s0   d|  d |d  d|  d |d   | d  S )NrA   r+   r_   rH   r^   r/   rc   r/   r/   r0   _motzkin  s    zmotzkin._motzkinc                 C   sJ   zt |}W n ty&   tdY n0 |dk r8tdt| |d S )Nrf  r   r+   )r&   rJ   r   rh  r~   r/   r/   r0   rn     s    zmotzkin.evalN)rU   rV   rW   rX   rY   rc  re  rg  r%   r   r{   rh  r|   rn   r/   r/   r/   r0   r`    s   $


r`  )r5   r   c                   s  ddl m} ddlm  ddlm dd | ||fddkrHtd	| durt| t	rbt
d
| sltjS t| turt| }t|}n<t| tu rtfdd|  D  dd |  D }d}|stjS t| }t| }t|}	n|dur| |stjS t|S |durt|tr\tfdd| D  dd | D }nPt|srt|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rV|	dkr@|dkr@tjS |	d |
krVt|
S |dk rj|du sp|r|du rg }d} | D ]2\}}t|D ]}|| g|  | d7 } qqt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 multiplicty 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r2   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   r[  rJ   rk  r/   r/   r0   ok  s
    
znD.<locals>.okNrA   zenter only 1 of i, n, or mz"items must be a list or dictionaryc                 3   s   | ]} |V  qd S r[   r/   )rD   _rl  r/   r0   r     rG   znD.<locals>.<genexpr>c                 S   s   i | ]\}}|r||qS r/   r/   rD   r   r$  r/   r/   r0   
<dictcomp>  rG   znD.<locals>.<dictcomp>c                 3   s"   | ]\}} |o |V  qd S r[   r/   )rD   rE   r   rn  r/   r0   r     rG   c                 S   s   i | ]\}}|| r||qS r/   r/   ro  r/   r/   r0   rp    rG   c                 3   s   | ]} |V  qd S r[   r/   rC   rn  r/   r0   r     rG   c                 S   s   g | ]}|r|qS r/   r/   rC   r/   r/   r0   rF     rG   znD.<locals>.<listcomp>zexpecting iterablec                 s   s   | ]\}}|| V  qd S r[   r/   ro  r/   r/   r0   r     rG   r+   r   c                 s   s   | ]
}d V  qdS rK  r/   rC   r/   r/   r0   r   	  rG   )expc                    s   g | ]\}} || qS r/   r/   )rD   rE   r   )rj  r2   r/   r0   rF   		  s   )&sympy.integrals.integralsri  #sympy.functions.special.polynomialsrj  Z	sympy.abcr2   countrJ   r*  r   r[  r   r   typer+  rQ   r"   r   r,  r2  r-  rR   r   r$   strrh   maxr{   r   r,   rI   r   r#   r   rq  absr   r   )rE   Zbruter5   r   ri  r   msrE  countsZnkeybigZnvalr$  r   rq  r/   )rj  rl  r2   r0   nD  s    ,






r|  )NF)NF)NF)NrA   F)N)NN)drX   mathr   collectionsr   typingr   r   tDictr   r   
sympy.corer   r   r	   r
   sympy.core.cacher   Zsympy.core.evalfr   sympy.core.exprr   sympy.core.functionr   r   sympy.core.logicr   Zsympy.core.mulr   sympy.core.numbersr   r   r   r   r   sympy.core.relationalr   r   sympy.external.gmpyr   (sympy.functions.combinatorial.factorialsr   r   r   sympy.ntheory.primetestr   r   sympy.utilities.enumerativer   sympy.utilities.exceptionsr!   sympy.utilities.iterablesr"   r#   r$   Zsympy.utilities.memoizationr%   sympy.utilities.miscr&   r   r'   r(   Zmpmath.libmpr)   r\   r1   ra   r6   r7   rZ   r}   r   r   r   r   r   r   r  r!  r   rL  r)  r;  r<  slicer=  r0  r8  r6  rH  rJ  rO  rM  rU  rT  rX  rY  rZ  r`  r|  r/   r/   r/   r0   <module>   s   	 T4Z   k  `_

B4
3
^


l
+
 }