K idZddlmZddlmZddlmZddlmZddl m Z m Z m Z m Z ddlmZddlmZdd lmZdd lmZmZmZdd lmZdd lmZdd lmZmZmZm Z m!Z!m"Z"ddl#m$Z$m%Z%m&Z&m'Z'ddl(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.ddl/m0Z0m1Z1m2Z2ddl3m4Z4ddl5m6Z6ddl7m8Z8m9Z9m:Z:m;Z;mZ>ddl?m@Z@mAZAddlBmCZCmDZDddlEmFZFmGZGmHZHddlImJZJddlKmLZLddlMmNZNddlOmPZPmQZQmRZRddlSmTZTddlUmVZVddlWmXZXmYZYddlZm[Z\d Z]e d!Z^Gd"d#eZ_Gd$d%eZ`Gd&d'eZaGd(d)eZbGd*d+eZcGd,d-eZdGd.d/eZeGd0d1eZfGd2d3eZgGd4d5eZhGd6d7eZiGd8d9eZjGd:d;eZkGd<d=eZlGd>d?eZmGd@dAeZnGdBdCeZoGdDdEeZpGdFdGeZqGdHdIeZrGdJdKeZsGdLdMeZtGdNdOeZuGdPdQevZwdRZxdSZyezdTeyZ{dUZ|dedVZ}ededWZ~edXZdedYZdZZed[Zd\Zed]Zdfd^Zed_Zdgd`ZGdadbeZdhdTdTdcddZyT)ia6 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. ) annotations)prod) defaultdict)Callable)SSymbolAddDummy)cacheit)Dict)Expr)ArgumentIndexErrorDefinedFunction expand_mul) fuzzy_not)Mul)EIpiooRationalInteger)Eqis_leis_gtis_lt) SYMPY_INTSremovelcmlegendrejacobi kronecker)binomial factorial subfactoriallog) Piecewise) factorint_divisor_sigma is_carmichael find_carmichael_numbers_in_rangefind_first_n_carmichaels)_primepi) _partition_partition_rec)isprime is_square)bernoulli_poly euler_poly genocchi_poly)cancel)MultisetPartitionTraversersympy_deprecation_warning)multisetmultiset_derangementsiterable)recurrence_memo)as_int)mpworkprec)ifibc2tt||dzSN)rrange)abs k/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/functions/combinatorial/numbers.py_productrI-s aQ  xcpeZdZdZedZedZedZedZedZ edZ y) 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 c4tdddt|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-methodsdeprecated_since_versionactive_deprecations_target)r9r2ns rHis_perfect_squarezcarmichael.is_perfect_squarens#! "(#I  |rJc.tddd||zdk(S)NzI divides can be replaced by directly testing n % p == 0. rOrPrQrr8)prUs rHdivideszcarmichael.divideszs'! "(#I  1uzrJc4tdddt|S)Nzi is_prime is just a wrapper around sympy.ntheory.primetest.isprime so use that directly instead. rOrPrQ)r9r1rTs rHis_primezcarmichael.is_primes#! "(#I  qzrJc4tdddt|S)Nzr is_carmichael is just a wrapper around sympy.ntheory.factor_.is_carmichael so use that directly instead. 1.13%deprecated-ntheory-symbolic-functionsrQ)r9r+rTs rHr+zcarmichael.is_carmichaels$! "(#J  QrJc6tdddt||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. r]r^rQ)r9r,)rKys rHr,z+carmichael.find_carmichael_numbers_in_ranges&! "(#J  0155rJc4tdddt|S)Nz find_first_n_carmichaels is just a wrapper around sympy.ntheory.factor_.find_first_n_carmichaels so use that directly instead. r]r^rQ)r9r-rTs rHr-z#carmichael.find_first_n_carmichaelss$! "(#J  (**rJN) __name__ __module__ __qualname____doc__ staticmethodrVrYr[r+r,r-rJrHrMrM;s0d         6 6 + +rJrMceZdZdZedZeedeje gdZ e d dZ dZ dZdZy) 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 ct|SN)_ifibrTs rH_fibzfibonacci._fibs QxrJNcB|dt|dzzjS)N_symexpandrUprevs rH_fibpolyzfibonacci._fibpolys$R4R=(0022rJch|tjurtjS|jr|Mt|}|dkr#tj|dzzt | zSt |j|S|dkr td|j|jt|Sy)NrrDzDFibonacci polynomials are defined only for positive integer indices.) rInfinity is_Integerint NegativeOnerirrm ValueErrorrvsubsrrclsrUsyms rHevalzfibonacci.evals  ?::  <<{Fq5==1q51IqbMAA"388A;//q5$&<==||A++D#66 rJc ddlm}m}tj|z|tj |ztj|zz z |dz S)Nr)sqrtcos)sympy.functionsrrr GoldenRatioPi)selfrUkwargsrrs rH_eval_rewrite_as_tractablez$fibonacci._eval_rewrite_as_tractables<- q 3qttAv;q}}a/?#??aHHrJc pddlm}d| z|dzd|dz|z|d dz|zz zdz S)NrrrrD(sympy.functions.elementary.miscellaneousrrrUrrs rH_eval_rewrite_as_sqrtzfibonacci._eval_rewrite_as_sqrtsDAA2wtAwT!Wq 0T!WHqL13D DEIIrJc tj|zdtj |zz z dtjzdz z SNrDr)rrrrUrs rH_eval_rewrite_as_GoldenRatioz&fibonacci._eval_rewrite_as_GoldenRatio s8 q 1q}}nq%8#881Q]]?1;LMMrJrk)rbrcrdrerfrmr=rOnerrrv classmethodrrrrrgrJrHririsn'RdAEE4()3*377"IJNrJric&eZdZdZedZdZy)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|tjurtjS|jrt|dzt|dz zSyrC)rrxryrirrUs rHrz lucas.eval5s@  ?::  <<QU#iA&66 6 rJc Xddlm}d| zd|dz|z|d dz|zzzS)NrrrrDrrrs rHrzlucas._eval_rewrite_as_sqrt=s7AA2wT!Wq(T!WHqL1+<<==rJN)rbrcrdrerrrrgrJrHrrs >77>rJrceZdZdZeeejejejgdZ eeejeje dzgdZ e d dZ dZdZy) 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$|d|dz|dzS)Nrorprgrts rH_tribztribonacci._tribps R48#d2h./rJrcb|dt|dzztdz|dzzjS)Nrrorrprqrts rH _tribpolyztribonacci._tribpolyus6R4R=(4748+;;CCEErJNc|tjurtjS|jr\t|}|dkr t d|t |j |S|j|jt|Sy)NrzITribonacci polynomials are defined only for non-negative integer indices.) rrxryrzr|rrrr}rrr~s rHrztribonacci.evalzs|  ?::  <<AA1u "@AA{syy|,,}}Q',,T377 rJc ddlm}m}dtj|dzzdz }d|dd|dzzz|dd|dzz zdz }d||dd|dzzzz|dz|dd|dzz zzdz }d|dz|dd|dzzzz||dd|dzz zzdz }||dzz||z ||z zz ||dzz||z ||z zz z||dzz||z ||z zz z} | S) NrcbrtrrprrD!)rrrr ImaginaryUnit) rrUrrrwrFrGcTns rHrz tribonacci._eval_rewrite_as_sqrtsFG !//DG+ +q 0 b1T"X:o& &b1T"X:o)> >! C 4QtBxZ(( (1a4R!DH*_0E+E E J Ad2$r( ?++ +aR!DH*_0E.E E J!a%j1q51q5/*!a%j1q51q5/*+!a%j1q51q5/*+ rJc ddlm}ddlm}m}|dd|dzz}d|zt j |zz|dzd|zz d zz }||t jzS) NrfloorriJfrrr)#sympy.functions.elementary.integersrrrrrTribonacciConstantHalf)rrUrrrrrGrs rH#_eval_rewrite_as_TribonacciConstantz.tribonacci._eval_rewrite_as_TribonacciConstants`=G s48|# $ UQ))1, ,1qs Q ?R!&&[!!rJrk)rbrcrdrerfr=rZerorrrrrrrrrrgrJrHrrIs$LaffaeeQUU+,0-0affaeeT1W-.F/F 8 8 "rJrceZdZUdZded<edZeje dde dde dd d Z d ddd d Z e ddZ ddZdZy ) 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 ztuple[Integer]argscd}tt|dz|dz }td|dzdzD]U}||t|d|zz zz }|t |dz d|zz dz|d|zz z}|t d|zdzd|zdzz}W|dzdk(rt |dzd |z }nt |dzd|z }|t|dz|z S)NrrrDr )rzr#rErrIr)rUsrFjs rH_calc_bernoullizbernoulli._calc_bernoulli s  QA& 'q!Q$(# -A Yq1Q3w'' 'A !a%!A#+/1qs73 3A (1Q37AaC!G, ,A  - q5A:!a%##a'AQ"Q&A8AE1%%%rJrDrrrp)rrDrrrrNcV|tjur||S|jrtjS|jdus|jdur+|(|j r|j rtjSy||tjurtjS|jr|dz jrtjS|jrt|}|dkDr6tj|\}}t!t|t|S|dz}|j"|}||kr|j$|St'|dz|dzdD]1}|j)|}||j$|<||j"|<3Sy|jr t+||Sy)NFrDir)rris_zero is_integeris_nonnegativeryis_nonpositiveNaNris_odd is_positiver is_Numberrzr?bernfracr_highest_cacherErr3) rrUrKrXqcasehighest_cachedirGs rHrzbernoulli.evalsr :q6M YY55L \\U "a&6&6%&?}!2B2Buu  YAEEzvv qs//vv Fs7;;q>DAq#CFCF331u!$d!3&::a=(~11q5!<+A++A.A$%CJJqM)*CLL&+#&[[!!Q' 'rJc ^ddlm}tdt|df| |d|z |zdfS)NrzetarDT)&sympy.functions.special.zeta_functionsrr(r)rrUrKrrs rH_eval_rewrite_as_zetazbernoulli._eval_rewrite_as_zetaEs2?!R1X!d1Q3l):D(ABBrJctd|jDsy|jdj|}t|jdkDr|jdntj j|}t |5|dk(rtjd}n|dk(r|tjdz }nhtj|r6|dk\r1|dk(rtj|ntj||}n| tjd|z |z}dddtj|S#1swYxYw)Nc34K|]}|jywrk is_number.0rKs rH z(bernoulli._eval_evalf..J211;;2rrD?)allr _to_mpmathlenrrr@r?mpfisintrbernpolyrr _from_mpmath)rprecrUrKress rH _eval_evalfzbernoulli._eval_evalfIs2 22  IIaL # #D ) ^a/TYYq\QUU F Ft L d^ +AvffQia"&&+o!a)*abll1oR[[A5Fb2771Q3?* +  d++ + +s B"E  ErkrD)rbrcrdre__annotations__rfrrrrrrrrrrrgrJrHrrsxbH  & & 8Aq>hq!n"bAQ RFqQ'H#(#(JC,rJrceZdZdZeeddgdZeeeje gdZ edZ e d dZ d dZy) 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 rDc\d}d}td|D]}|||z z|z}||||zz }|SrC)rErUrurrFks rH_bellz bell._bellsN  q! AQU q A T!W A rJcd}d}td|dzD]!}|||z dzz|dz z}||||dz zz }#tt|zSr)rErrrrs rH _bell_polyzbell._bell_polysh  q!a% !AQUQYAE*A T!a%[ A !$(##rJc\|dk(r|dk(rtjS|dk(s|dk(rtjStj}tj}td||z dzD]9}||tj ||z |dz |z||dz zz }|||z z|z };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` rrDr)rrrrEr_bell_incomplete_polyr)rUrsymbolsrrFms rHrzbell._bell_incomplete_polys" Fa55L1f!q&66M FF EEq!a%!)$ A T//Aq1ug'')0Q8 8AQU aA !}rJNc|tjur|tjStd|js|jdur td|j r|j r||#t|jt|S|.|jt|jt|S|jt|t||}|Syy)NzBell polynomial is not definedFza non-negative integer expected)rrxr| is_negativerryrrrrzrr}rrr)rrUk_symrrs rHrz bell.evals  ?}zz! !ABB ==ALLE1>? ? <@aVaeeT]#$$$8& DrJrceZdZUdZiZded<eddZejfdZ ddZ ddZ dd Z ejfd Zd Zdd Zd ZddZy)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/ z(dict[Integer, Callable[[int], Rational]]harmonic_cacheNc ddlm}tjur||Stj|jrtj Sjr|S|tj urijrtjSttjrtj Sttjr|Syjr3jr'tdz |dztdz z dz z S|jr|jrNjdusjdur2tjurtjStjS|j rjrO|j"vr#t%dgfd}||j"<|j"t'|St)fdt+dt'|dzDSyy)NrrrDFc<|dtj|zz zS)Nrp)rr)rUrurs rHfzharmonic.eval..fs#'8aeeadl#::rJc3*K|] }| z ywrkrg)rrrs rHrz harmonic.eval..sCQ!WCs)rrrrrrrxrrrrryrrrComplexInfinityrr r=rzr rE)rrUrrr s ` rHrz harmonic.evals? :q6M 9A 9966M YYH !**_}}uu q!%%zz!q!%%Aw! \\a..ac1Q3')AaC.8QqSA A \\}}!,,%"71;K;Ku;T,-Jq((AAEEA<< 2 22(!-;.;01**1-03--a0Q88CeAs1vz.BCDD rJc ddlm}m}|jry|jrlt |d|dzt jzt|dft j|z||dz d||dz |dzz z||z dfSyy)Nr)gamma polygammarDT) 'sympy.functions.special.gamma_functionsrrrrr(r EulerGammarr{)rrUrrrrs rH_eval_rewrite_as_polygammaz#harmonic._eval_rewrite_as_polygammasL <1aI]]A%1Q3):YqsAaC=P)PQ!H"$% %*>coo8=c1b8IJ1aeeTAX.JhW[nM]]F<'^^9>q#r9JKAquufdQh/KxX\~N^^F<'}}'')1FAI## !--APQEJIVVc ASa!eai1a)<>Gd1acl*33Kd3K K rJcXtd|jDsy|jdj|}t|jdkDr|jdntj j|}t j|r|dkrtjSt|5|dk(rt j|}n/t j|t j||dzz }dddtj|S#1swYxYw)Nc34K|]}|jywrkrrs rHrz'harmonic._eval_evalf..rrrrD)rrrrrrr?rrr@rrr r)rrrUrrs rHrzharmonic._eval_evalfs2 22  IIaL # #D ) ^a/TYYq\QUU F Ft L 88A;1q555L d^ 3Avkk!nggaj2771ac?2  3   d++  3 3s 7A D  D)cddlm}t|jdk(r|j\}}n|jdz\}}|dk(r|||dz|dzzSt)NrrrrrD)rrrrr)rargindexrrUrs rHfdiffzharmonic.fdiffsZ? tyy>Q 99DAq99t#DAq q=tAaC1~% %$ $rJrkrrDN)rbrcrdrer rrrrrrrrrrr4rrrArgrJrHrrsnAH@BN<AEE@/0ee%'''*+9 "HL , %rJrc8eZdZdZeddZddZddZdZy)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|jrtjS|tjur5|tjdz Sddlm}||dzdz ||dz z S|jdus|jdury|u|jr|jrtjS|jr@ddl m}|j|j }|j"|d}t%|Sy|jrdd lm}t+|}||d }|rt-d |Drt/d |Drsddl m}t1|Dcgc]}|j2s|j4c}} t7| 5|j8||}dddt;j<| St?||Sycc}w#1swY1xYw) Nrrr"rDFr?T)exact) pure_complex)or_realc3PK|]}|jxs |j ywrk)is_FloatryrrFs rHrzeuler.eval..xs E1AJJ6!,,6Es$&c34K|]}|jywrk)rKrLs rHrzeuler.eval..ys51AJJ5r) rrrr{rrr#rrrrrrmpmathr?rreulernumrsympy.core.evalfrHrzranyminrK_precr@ eulerpolyr rr4) rrUrKr#r?rrHreimrFrs rHrz euler.eval_s 9955L !-- yttAv GAaC7#gacl2 2 \\U "a&6&6%&?  YxxAMMvv %LL)!bkk!40s|#  [[ 5AA40DEEE555%T@QZZAGG@Ad^-&",,q!,C-((d33a# #A--sG&GG  Gc ddlm}||jrtdd}tdd}|dz }tj ||t ||tj|z|d|zz d|zdzzzzd|ztj |zz|zz |d|f|dd|zdzfz}|S|rOtdd}|t ||t|zd|zz |tjz ||z zz|d|fSy) NrrrTr rrrD) rris_evenr rrr#r{rDr)rrUrKrrrrEms rHrzeuler._eval_rewrite_as_Sums1 9c4(Ac4(AAA//CHQNammQ>N?@1Q3w!A#PQ'>R?S-Ta4**Q.-023Q)<>?AaC!G_%NNBI c4(Ax1~eAh.q!t3QZ1q54IIAqRS9U U rJc D|Sttjdz t|dfd|z t |dztj z|dzz dfSddlm}t||dzdz ||dz z t|dft |dz| |dzz dfS)NrrprDTrr")r(rrrgenocchirrr#)rrUrKrr#s rH_eval_rewrite_as_genocchizeuler._eval_rewrite_as_genocchis 9add1fbBi0 !tehqsAFF&;;qsCTJL LC'1Q3'*WQqS\92a9E#AaC++qs3T:< .rrrrFrDrprr)rrrNr?rrr@rrOrTrr#rr r)rrr?rrKrr`s rHrzeuler._eval_evalfsi2 22 '*499~': ! d# 1 LL  = T"A d^ rxx{qAv() kbkk!n|r||Aq7I7#$9"%%*"**ac1W2E  STUVSV2WC yaAwrwwr1~AaC7277A2!Qw;O0OOPC91a4KC   d++ s C E66E?rk) rbrcrdrerrrr[rrgrJrHrDrD s.Ob$$B V<,rJrDc`eZdZdZedZddZdZdZddZ dZ dZ d Z d Z d Zd Zy )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 cddlm}|jr |js|jrN|j rBd|z||t jzz|t j||dzzz S|jrH|j r;|dzj rt jS|dzjr tddSyyy)NrrrrrDrp) rrryr is_nonintegerrrrrrrr)rrUrs rHrz catalan.evalsA LLQ-- OO a4a!&&j))5=q1u+EF F LLQ]]A""vv AA&+LrJcddlm}ddlm}|jd}t ||d|t jz|d|dzz |dzzS)Nrr&rrr)r*r'rrrr`rr)rr@r'rrUs rHrAz catalan.fdiffsM>E IIaLqz9QAFF 3i1q56IICPQFRSSrJc ,td|z||dzz SNrrD)r#rs rH_eval_rewrite_as_binomialz!catalan._eval_rewrite_as_binomials!QQ''rJc Ttd|zt|dzt|zz Srf)r$rs rH_eval_rewrite_as_factorialz"catalan._eval_rewrite_as_factorials&1~1Q3)A,!>??rJc ddlm}d|z||tjzz|tj||dzzz S)Nrrbrr)rrrr)rrU piecewiserrs rH_eval_rewrite_as_gammazcatalan._eval_rewrite_as_gammas;A!tE!aff*%%uQVV}U1q5\'ABBrJc 0ddlm}|d|z | gdgdS)Nr)hyperrDr)sympy.functions.special.hyperrn)rrUrrns rH_eval_rewrite_as_hyperzcatalan._eval_rewrite_as_hyper"s 7a!eaR[1#q))rJc ddlm}|jr |js|St ddd}|||z|z |d|fS)Nr)ProductrT)rpositiver)sympy.concrete.productsrrrrr )rrUrrrrs rH_eval_rewrite_as_Productz catalan._eval_rewrite_as_Product&sB3 !1!1K #td 3A{Q1I..rJcl|jdjr|jdjryyyNrTrrrrs rH_eval_is_integerzcatalan._eval_is_integer-s/ 99Q< " "tyy|'B'B(C "rJc8|jdjryyrwrrrys rH_eval_is_positivezcatalan._eval_is_positive1 99Q< & & 'rJcr|jdjr|jddz jryyy)NrrT)rrrrys rH_eval_is_compositezcatalan._eval_is_composite5s4 99Q< " " ! q(8'E'E(F "rJcddlm}|jdjr |j |j |Sy)Nrrb)rrrrrr)rrrs rHrzcatalan._eval_evalf9s5A 99Q< ! !<<&2248 8 "rJNr)T)rbrcrdrerrrArgrirlrprurzr}rrrgrJrHr`r`sRM^ ' 'T (@C */9rJr`c\eZdZdZed dZddZddZdZdZ dZ d Z d Z d Z d Zy)rZaY 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 NcV|tjur||S|jdus|jdury|X|jr|dz j rtj S|jr ddtd|zz zt|zSy|jr t||Sy)NFrDr) rrrrrrrrrr5)rrUrKs rHrz genocchi.evalys :q6M \\U "a&6&6%&?  YxxQqS--vv AadAgI155[[ A& &rJc |dk(r8|jr,|jr ddtd|zz zt|zSdt||d|zt||dzdz zz zSr)rrrr)rrUrKrs rH_eval_rewrite_as_bernoulliz#genocchi._eval_rewrite_as_bernoullisd 6allq'7'7!A$' ?Yq\1 1IaOadYq1Q3!)-D&DDEErJc 2ddlm}d|z|d|z |zS)Nr) dirichlet_etarorD)rr)rrUrKrrs rH_eval_rewrite_as_dirichlet_etaz'genocchi._eval_rewrite_as_dirichlet_etasH!tmAaC+++rJct|jdkDr|jddk7ry|jd}|jr|jryyy)NrDrT)rrrrrrUs rHrzzgenocchi._eval_is_integersJ tyy>A $))A,!"3  IIaL <A $))A,!"3  IIaL <A $))A,!"3  IIaL <A $))A,!"3  IIaL <A $))A,!"3  IIaL <A $))A,!"3  IIaL!}}rJctd|jDr$|jtj |Sy)Nc34K|]}|jywrkrr^s rHrz'genocchi._eval_evalf..s.qq{{.r)rrrrr)rrs rHrzgenocchi._eval_evalfs3 .DII. .<< *66t< < /rJrkr)rbrcrdrerrrrrzrr}rrrrrgrJrHrZrZFsJ0d ' 'F , !%0=rJrZc>eZdZdZedZdZdZdZdZ dZ y) 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 |tjurtjS|tjurtjS|jrtjS|dk(r t d S|dk(rdtj zS|jrn|jr |jrtt|S|jr5ddl m}| dz }t|zt!dd|zz d|zz|| zSyy)NrprrorrrDr)rrrxrrr'CatalanryrrWabsrDrrrrr)rrUrrs rHrz andre.eval s :55L !**_::  9955L "WF7N "Waii<  \\AII58}$GBqD!thqAvq!t44tQBx??rJc ddlm}ddlm}ddlm}d||dzzdt z|dzzz ||dztjdz |t |z||dztddz zz zS) Nr)rrbrrrDrr) r+rrrrrrrr)rrrrrrs rHrzandre._eval_rewrite_as_zeta sr@A?51:~21 -ac1557#c"Q$i$qsAaDF2C&CCE ErJc ddlm}t |dzz|| tzt|dzz|| t zzS)Nr)polylogrD)rrr)rrrrs rH_eval_rewrite_as_polylogzandre._eval_rewrite_as_polylog's>Bac{WaR^+a!A#h!aR.HHHrJcV|jd}|jr|jryyyrwrxrs rHrzzandre._eval_is_integer+s( IIaL <>> 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(|jdur td|jdurtjS|j dus|tj urtj S|jdurttt|Sy)NFn should be an integerT) r TypeErrorrrrrrryr/r>rs rHrzpartition.evalgss <<5 45 5 ==D 66M 99 QUU 55L <<4 Zq *+ + rJc<|jdjduryyrwr|rys rHr}zpartition._eval_is_positivers 99Q< & &$ . /rJcv|jd}dD]%\}}||k(s ||z|k(stjcSy)Nr))rr)r) r)rrr)rrrUrXrems rH _eval_Modzpartition._eval_Modvs< IIaL/ FAsAv!a%3,vv  rJN) rbrcrdrerrrrr}rrgrJrHrrDs/>JN,,rJrc@eZdZdZdZdZeejfdZ y) 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 |jdur td|jdur td|jdur td|jdur td|j durd||zzS|t jurt jS|jdur|jdur0tt|jDcgc]}|dz c}S|jdur't tt|t|S|jdurPtt|jDcgc]%\}}t!|||dzzzdz ||zdz z 'c}}Syycc}wcc}}wNFrn should be a positive integerzk should be an integerz!k should be a nonnegative integerTrD)rrrr|rr[rrryrrr)valuesr*r>itemsr6)rrUrerXs rHrzdivisor_sigma.evalsb <<5 45 5 ==E !=> > <<5 45 5  u $@A A :: q!t8O :55L <<4 yyD IaL,?,?,ABqQUBCC||t#q 6!9=>>yyE!S\]^S_SeSeSgh41aVQAE^a%7AqD1H$EFhii" Bis  E> *F N rbrcrdrerrrrrrrgrJrHrr~s/'PJKuujjrJrc@eZdZdZdZdZeejfdZ y)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 |jdur td|jdur td|jdur td|jdur td|j durd||zzS|j r;tt|jDcgc]\}}d|||zzzc}}Sycc}}wr) rrrr|rr[ryrr)r)rrUrrXrs rHrzudivisor_sigma.evals <<5 45 5 ==E !=> > <<5 45 5  u $@A A :: q!t8O << ! 0B0B0DE11qs8EF F Es(C NrrgrJrHrrs/3hJKuu G GrJrc(eZdZdZdZdZedZy)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|jdur td|jdur td|jdus|jdur t d||zj durt jS|t jurt jS|jdur6|jdur't tt|t|Syy)NFa should be an integerzp should be an integerz p should be an odd prime integerT) rrr[rr|rrrrryr r>)rrFrXs rHrzlegendre_symbol.eval)s <<5 45 5 <<5 45 5 :: !((e"3?@ @ E??d "66M :55L <<4 ALLD$8XfQi34 4%9 rJNrbrcrdrerr[rrrgrJrHrr s%8JH 5 5rJrc(eZdZdZdZdZedZy) 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|jdur td|jdur td|jdus|jdur t d|t j us|t j urt j S||zjdurt jS|jdur6|jdur't tt|t|Syy)NFzm should be an integerrz#n should be an odd positive integerT) rrrrr|rrrrryr!r>)rrrUs rHrzjacobi_symbol.evalps <<5 45 5 <<5 45 5 ==E !QXX%6BC C :aee55L E??d "66M <<4 ALLD$8VF1Ivay12 2%9 rJNrrgrJrHrr9s&2fJH 3 3rJrc(eZdZdZdZdZedZy)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 TFcX|jdur td|jdur td|tjus|tjurtjS|jdur6|jdur'tt t |t |Syy)NFrrT)rrrrryr"r>)rrFrUs rHrzkronecker_symbol.evals <<5 45 5 <<5 45 5 :aee55L <<4 ALLD$8Yvay&)45 5%9 rJNrrgrJrHrrs%.JH66rJrc(eZdZdZdZdZedZy)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|jdur td|jdur td|jdurt j S|t jurt jSd}dtj|DD]\}}|jdur|jdur|jdur|jdurtt j|}|durt j}m|jdus|t|}td|jDrt j}|dust!|dzrt j nt j}||}||z}y|S)NFrrTc3<K|]}|jywrk) as_base_exp)r_s rHrzmobius.eval..s?Q]]_?sc3&K|] }|dkD ywrBrgrvs rHrzmobius.eval..s;Q1q5;r)rrrr|r[rr{rr make_argsrrryr)rQrr)rrUr/rrltfactorsrs rHrz mobius.evals@ <<5 45 5 ==E !=> > :: == :55L?cmmA.>? DAq||t# (=||t# (=155!_:VVF\\T)'lG;'..*:;;!"u-0\A-=AMM155!>%&F"aKF# $ rJNrrgrJrHrrs&+XJHrJrc(eZdZdZdZdZedZy)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>|jdur td|jdur td|jdurt j S|t j urt jS|jdurt tt|SyNFrrT) rrrr|r[rrrryrr)rs rHrz primenu.evals <<5 45 5 ==E !=> > :: 55L :66M <<4 S1&' ' rJNrbrcrdrerrrrrgrJrHrrs&!DJN ( (rJrc(eZdZdZdZdZedZy) 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 TcZ|jdur td|jdur td|jdurt j S|t j urt jS|jdur+t tt|jSyr) rrrr|r[rrrrysumr)rrs rHrzprimeomega.evalRs <<5 45 5 ==E !=> > :: 55L :66M <<4 S1,,./0 0 rJNrrgrJrHrr+s&"FJN 1 1rJrc(eZdZdZdZdZedZy)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|jdur td|jdur td|tj urtj S|j dur|dz St|tr)t td|jDS|jdur2t tdt|jDSy)NFrrTrDc3>K|]\}}||dz z|dz zywrBrgrrXrs rHrztotient.eval..s$?TQ!ac(AaC.?c3>K|]\}}||dz z|dz zywrBrgrs rHrztotient.eval..s$JTQ!ac(AaC.Jr) rrrr|rrr[r8r rrryr)rs rHrz totient.evals <<5 45 5 ==E !=> > :55L :: q5L a T?QWWY??@ @ <<4 TJYq\5G5G5IJJK K rJNrbrcrdrerrrrrgrJrHrr`s'<JK L LrJrc(eZdZdZdZdZedZy)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 j|jdur td|jdur td|tj urtj S|j dur|dz St|trQd}d|vrd|dkr d|ddz zn|d}t tt|gd|jDS|jdur]tt|d\}}|sd}n d|krd|dz z}t t|gdt|jDSy) NFrrTrDrc3K|]6\}}|dk7s t|dz t|t|dz zz8yw)rrDN)rzrs rHrz'reduced_totient.eval..s;"]AVW[\V\3qs8CFC!H,<#<"]s >.>c3>K|]\}}|dz ||dz zzywrBrgrs rHrz'reduced_totient.eval..s$NAqsA!HnNr)rrrr|rrr[r8r rrzrryrr))rrUts rHrzreduced_totient.evals  <<5 45 5 ==E !=> > :55L :: q5L a AAv)*QqTQ1Q4!8_qtSQ^"]"]^_ _ <<4 #a&!$DAqQ!a%LSON19K9K9MNOP P rJNrrgrJrHrrs'<JKQQrJrc(eZdZdZdZdZedZy)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 Tch|tjurtjS|tjurtjS|jdur t dt |tddurtjS t|}tt|S#t $rYywxYw)NFzn should be a realrT) rrxNegativeInfinityris_realrrrzr.rs rHrz primepi.evals  ?::  "" "66M 99 01 1 AaD>T !66M AA!~   s B%% B10B1NrrgrJrHrrs&"FJN  rJrceZdZdZy)_MultisetHistogramrgN)rbrcrd __slots__rgrJrHrr sIrJrrproNcxttr}tdjDstt j}t fdD}t Dcgc]}|dkDs |c}||gzStt}t|}t}||k(rdg|z||gzt Stt|t|}ttt|d|z}D]} ||| xxdz cc<t|Scc}w)a6Return 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. c3JK|]}t|txr|dk\yw)rN)r8rzrs rHrz&_multiset_histogram.. s#EQ:a%0!q&0Es!#c34K|]}|dkDs dyw)rrDNrg)rrrUs rHrz&_multiset_histogram.. s-!AaD1HA-s rrDr) r8dictrrr|rrlistsetrziprE_multiset_histogram) rUtotrrrlenslennrdrs ` rHrr s!TE!((*EE !((*o-q--!"?AadQh1Q4"?5#,"NOO G F1v1v 4<DD$<'A%a( ( Qd $ % U4[$t), - A adGqLG "1%%#@s . D7<D7c t|}tt|||S#t$r"ttt |||cYSwxYw)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>r|r_nPr)rUr replacements rHnPr1 sUvD 1I 3q![) ** Ds.q11kBCCDs #(A Ac |dk(ryttrY|!tfdtdzDSr|zS|kDry|k(r t |S|dk(rSt |z dzStt rv|(tfdttdzDSr t|zS|tk(r;t |ttDcgc]}|dkDs t |c}z S|tkDry|dk(r tSd}ttttD]}|s txxdzcc<|dk(rHd|<txxdzcc<|tt |dz z }txxdz cc<d|<n5|xxdzcc<|tt |dz z }|xxdz cc<txxdz cc<|Sycc}w)NrrDc38K|]}t|ywrkrrrrUrs rHrz_nP..{ sD!s1a-Dc38K|]}t|ywrkr r s rHrz_nP.. sH!s1a-Hr )r8rrrEr$rIr_N_ITEMSr_Mrrr)rUrrrrs` ` rHrrs s Av!Z 9DuQU|DD D a4K U !VQ<  !VHAEAIq) ) A) * 9HuQrUQY7GHH H V9a<  !B%ZQ<AbE%KqQUil%K LL L 2Y !VV9 CQA3qu:& t" Q419AaDfINI31!4a!e<>> 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. rrDrNrp) rrpopextendrrErRreversedrrz enumerate) rUordneedrvniNwasrrevrrs rH _AOP_productr sJ6 QA a&C !Ga>> 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 rc38K|]}t|ywrknCr s rHrznC.." Cr!Q ,Cr rDrzk cannot be negativec3&K|] }|dz ywrBrg)rrs rHrznC.., s1aAE1rc38K|]}t|ywrkr!r s rHrznC..- r#r )r8rrrEr|r#rrrrr"rrtupler)rUrrrs` ` rHr"r" s%D!Z 9!t CeAElCC C q534 4 AEAIq) )1~!'( bE 911R5111CeAElCC C aiK0 0 1a!e*_V9  1a&[E!B%L)!,,%a(![99rJcR||cxk(rdk(rtjSd||fvrtjS||k(rtjS||dz k(r t|dS||dz k(rd|zdz t|dzdz S||dz k(rt|dt|dzSt ||S)NrrDrrr)rrrr# _stirling1rUrs rH_eval_stirling1r*: sA{{uu QF{vv  Avuu a!e1~ a!e!a!Q')) a!e1~hq!n,, a rJcddgdg|dz zz}td|dzD]5}tt||ddD]}|dz ||z||dz z||<7t||SNrrDrrprErRrrUrrowrrs rHr(r(M s a&!ac C 1ac]/s1QxB' /AcSV^c!A#h.CF // 3q6?rJc,||cxk(rdk(rtjSd||fvrtjS||k(rtjS||dz k(r t|dS|dk(rtjS|dk(rt d|dz zdz St ||S)NrrDr)rrrr#r _stirling2r)s rH_eval_stirling2r2V sA{{uu QF{vv  Avuu a!e1~ auu aq1q5zA~&& a rJcddgdg|dz zz}td|dzD]2}tt||ddD]}|||z||dz z||<4t||Sr,r-r.s rHr1r1i s a&!ac C 1ac]+s1QxB' +AQZ#ac(*CF ++ 3q6?rJcVt|}t|}|dkr td||kDrtjS|rt ||z dz||z dzS|r#tj ||z zt ||zS|dk(r t ||S|dk(r t ||Std|z)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 rzn must be nonnegativerDrzkind must be 1 or 2, not %s)r>r|rrr2r{r*)rUrrkindsigneds rHstirlingr7r sl q Aq A1u0111uvv q1uqy!a%!)44 }}q1u%oa&;;; qyq!$$ q!$$6:;;rJc ||kDs|dkry|d|fvry|dk(ry|dk(r|dzS||z }|dkr|Sd|z|k\rBt|}||z dkDr-|ttjt||z z}|Sdg|z}t d|dzD].}t |dz|D]}||xx|||z z cc<|dz}0dt|d|z dzS)zxReturn the partitions of ``n`` items into ``k`` parts. This is used by ``nT`` for the case when ``n`` is an integer.rrDrrN)r0r fetch_itemslicerE)rUrrrrXrrs rH_nTr; s  1uAQF{AvAv!t  AAAvsax Q q519 3~00q1u>? ?C  AA 1a!e_Aq/ A aDAa!eH D  Q Aa!efI rJcnttrH| tSt|tr+tt|}t t |Stt sN tt}|dkrtt|S|tk(r t|tt}||dk(ry|d|fvry|dk(s|dk(rO|Mt|d\}}tfdtd|dzD}|s|t!|dzz}||dz }|S|t"k(r| t%|St'||St)}||j+t,Sd}|j/t,|dz |D]}|dz } |S#t$rtYwxYw)apReturn 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 rDrc36K|]}t|ywrkr!)rrrUs rHrznT..n s3aAq3sr)r8rrr>rr;rrrnTrErrrdivmodrr"rrr7r7count_partitionsr enum_range) rUrr0rrrrrdiscards ` rHr>r> sR!Z 9Q<  a $q Aq A3q!9% % a+ , 'CF AAv#a&!}$c!f!HO "AyQ!VQF{AvaAIa|1 35AE?3 3 "Q(A+ B 9 !GB AfI~ 97N1~"$Ay!!!B%(( C<<"qsA. q J9 '#A&A 's+-FFF43F4ceZdZdZedZedZedZeee je jgdZ e dZ y)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 t|}|dkDrC|dvryd}d}d}||kr,d|zdz|zd|zdz |zz|dzz }|dz }|}|}||kr,||k(ryyy#t$rYywxYw)NFr)rDrTrDrr)r>r|)rUtn1tnrrFs rH is_motzkinzmotzkin.is_motzkin s q A q5F{CBAq&cAgr\QqS1WcM1AE:Q q& Qw+  s A A"!A"c:d|cxkr|krn tdg}|dcxkr|krnn|jdd}d}d}||krK||k\r|j|d|zdz|zd|zdz |zz|dzz }|dz }|}t|}||krK|Std)NrrDrrzEThe provided range is not valid. This condition should satisfy x <= y)appendrzr|)rKr`motzkinsrFrGrrFs rHfind_motzkin_numbers_in_rangez%motzkin.find_motzkin_numbers_in_range s ;Q;$de e#HA{{"CBA'7OOB'cAgr\QqS1WcM1AE:QV 'Ode erJcB t|}|dkr tddg}|dk\r|jdd}d}d}||krF|j|d|zdz|zd|zdz |zz|dzz }|dz }|}t|}||krF|S#t$r tdwxYw)N.The provided number must be a positive integerrrDrr)r>r|rJrz)rUrKrFrGrrFs rHfind_first_n_motzkinszmotzkin.find_first_n_motzkins s Oq A q5MN N3 6 OOA   1f OOB A#'21q# -A6A FACQB 1f# OMN N Os B BcHd|zdz|dzd|zdz |dzz|dzzS)NrrDrprrorgrts rH_motzkinzmotzkin._motzkin s:1q$r("acAgtBx%77QUCCrJc t|}|dkr tdt|j|dz S#t$r tdwxYw)NrNrrD)r>r|rrQrs rHrz motzkin.eval s] Oq A q5MN Ns||AE*++  OMN N Os :AN)rbrcrdrerfrHrLrOr=rrrQrrrgrJrHrDrD s"H4ff*,aeeQUU^$D%D,,rJrD)rUrcddlm}ddlm}ddlm}d|||fj ddk7r td|t|tr td |stjSt|turt|}t!|}n[t|turJt#fd |j%D|j'D cic] \} } | s | |  }} } d}stjSt)|j%} t!|j%} t+|} n5|%||stjSt-|S| t|trLt#fd |j'D|j'D cic]\} } | | zs | | } } } nbt/|st|t0r>> 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)laguerrerKcZt|ts td|dkr tdy)Nzexpecting integer valuesrzvalue must not be negativeT)r8rrr|rVs rHokznD..ok7 s.!Z(67 7 q59: :rJNrzenter only 1 of i, n, or mz"items must be a list or dictionaryc3.K|] }|ywrkrg)rrrXs rHrznD..I s*!1*c3HK|]\}}|xr|ywrkrg)rrrrXs rHrznD..X s#6DAq1"Q%6s"c3.K|] }|ywrkrg)rrrXs rHrznD..\ s!!1!rZzexpecting iterablec3,K|] \}}||zywrkrg)rrrs rHrznD..b s/1!/srDrc3 K|]}dywrBrgr^s rHrznD..y s?1?s )exp)&sympy.integrals.integralsrT#sympy.functions.special.polynomialsrU sympy.abcrKcountr|r8rrrrtyperrr:rrrrrr%r<strrzmaxrr$rErrr;r*r_rrr)rbruterUrrTrUrKrmsrrrcountsnkeybignvalrr_rXs @rHnDrm sVX4< 1ayt!566} a $@A A66M 7$ QA!B !W_ *qxxz* *#$779241a!Q$2B2A66M  "))+&2w  166MA  a  6AGGI6 6'(wwy8tq!AaCad8F8 a[Jq#.QA !q! !!1Qqq12F01 166M / / /6==?#  c&k C axD!! v;D 1uqyvv  1uz 1955L !8s?S> !1u% 9AA  1qAHHaSUOFA s?&;A&>??@@: 3yaR&,lln/6"aA/6*7"79:Ar DE FFc392</6s* O"O, O :O OOO)NF)NrFrkr)re __future__rmathr collectionsrtypingr sympy.corerrr r sympy.core.cacher sympy.core.containersr sympy.core.exprr sympy.core.functionrrrsympy.core.logicrsympy.core.mulrsympy.core.numbersrrrrrrsympy.core.relationalrrrrsympy.external.gmpyrrrr 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/r0sympy.ntheory.primetestr1r2sympy.polys.appellseqsr3r4r5sympy.polys.polytoolsr6sympy.utilities.enumerativer7sympy.utilities.exceptionsr9sympy.utilities.iterablesr:r;r<sympy.utilities.memoizationr=sympy.utilities.miscr>rNr?r@ mpmath.libmprArlrIrrrMrirrrrrrDr`rZrrrrrrrrrrrrrr&rrrr:rrrrrr"r*r(r2r1r7r;r>rDrmrgrJrHrs##,,$& OO&>>99TT6:__+@6LL(B@OO7'&! c{x+x+DNNNNp*>O*>hP"P"tt,t,|OD?ODrI%I%f],O],NH9oH9dB=B=Xi,Oi,d77t@jO@jFEG_EGP-5o-5`D3OD3N$6$6NM_M`1(o1(h2121j/Lo/Ld7Qo7Qt5o5~  4&:?+D 1 1h 0  0 f[:|&  &  i