Package: labmath
labmath version 2.2.0This is a module for basic math in the general vicinity of computational number theory.  It includes functions associated with primality testing, integer factoring, prime counting, linear recurrences, modular square roots, generalized Pell equations, the classic arithmetical functions, continued fractions, partitions, Størmer’s theorem, smooth numbers, and Dirichlet convolution.  Integer arithmetic is used wherever feasible.FunctionsWe make a few imports:frommultiprocessingimportProcess,QueueasmpQueuefromitertoolsimportchain,count,groupby,islice,tee,cycle,takewhile,compress,product,zip_longestfromfractionsimportFractionfromrandomimportrandrangefrommathimportlog,log2,ceil,sqrt,factorial;inf=float('inf')fromheapqimportmergetry:fromgmpy2importmpz;mpzv,inttypes=2,(int,type(mpz(1)))exceptImportError:mpz,mpzv,inttypes=int,0,(int,)labmathversion="2.2.0"Thenewfunctions provided by this module are as follows.  Further details, including examples and input details, are available in docstrings and accessible via the built-inhelpfunction.primegen(limit=inf)Generates primes less than the given limit (which may be infinite) lazily via a segmented sieve of Eratosthenes.  Memory usage depends on the sequence of prime gaps; on Cramér’s conjecture, it is O(sqrt(p) · log(p)2).rpn(instr)Evaluates a string in reverse Polish notation.  The acceptable binary operators are+ - * / // % **and correspond directly to those same operators in Python3 source code.  The acceptable unary operators are! #.  They are the factorial and primorial, respectively.  There are four aliases:xfor*,xxfor**,ffor!, andp!for#.iterprod(l)Product of the elements of any iterable.  The product of an empty iterable is 1.  DEPRECATED: now that Python 3.8 hasmath.prod, this function definition will in a future version be replaced with the statementfrom math import prod.  That will probably happen when PyPy3 supports Python 3.8.listprod(l)Product of the elements of a list.  The product of the empty list is 1.  We use a binary algorithm because this can easily generate huge numbers, and callingreduce(lambda x,y: x*y, a)in such situations is quite a bit slower due to the time-complexity of multiplication.  However, the size of the problem required to make this superior toiterprod()is quite large, soiterprod()should usually be used instead.polyval(f,x,m=None)Evaluates a polynomial at a particular point, optionally modulo something.binomial(n,k)The binomial coefficient nCr(n,k).  DEPRECATED: now that Python 3.8 hasmath.comb, this function definition will in a future version be replaced with the statementfrom math import comb.  That will probably happen when PyPy3 supports Python 3.8.powerset(l)Generates the powerset of a list, tuple, or string.  The yielded objects are always lists.primephi(x,a,ps,phicache={})Legendre’s phi function.  Helper function forprimepi.primepi(x,ps=[],picache={},phicache={},sqrts={})Computes the number of primes ≤xvia the Meissel-Lehmer method.  The argumentsps,pichache,phicache, andsqrtsare for internal use only.primesum(n)Sum of primes ≤n.altseriesaccel(a,n)Convergence acceleration for alternating series.  This is algorithm 1 fromConvergence Acceleration of Alternating Seriesby Cohen, Villegas, and Zagier(pdf), with a minor tweak so that thed-value isn’t computed via floating point.riemannzeta(n,k=24)Computes the Riemann zeta function by applyingaltseriesaccelto theDirichlet eta function.  Should be rather accurate throughout the complex plane except nearnsuch that 1 = 2n-1.zetam1(n,k=24)Computesriemannzeta(n, k) - 1by applyingaltseriesaccelto the Dirichlet eta function.  Designed to be accurate even whenriemannzeta(n)is machine-indistinguishable from 1.0 — in particular, whennis a large real number.riemannR(x,n=None,zc={})Uses theGram seriesto computeRiemann’s R function, which is a rather good approximation toprimepi.  The argumentzcis a cache of zeta values.nthprimeapprox(n)Produces an integer that should be rather close to thenthprime by using binary splitting on Riemann’s R function.nthprime(n)Returns thenthprime (counting 2 as #1).  This is done with some efficiency by usingnthprimeapproxas an initial estimate, computingprimepiof that, and then sieving to remove the error.gcd(a,*r)Greatest common divisor of any number of values.  Now thatmath.gcdsupports any number of arguments, this function definition will in some future version be replaced withfrom math import gcd.xgcd(a,b)Extended Euclidean altorithm: returns a tuple (g,x,y) such thatg= gcd(a,b) andg=a·x+b·y.modinv(a,m)Returns the inverse ofamodulom, normalized to lie between0andm-1.  Ifais not coprime tom, returns 1.  DEPRECATED: as of version 3.8, this can be computed using Python’s built-in pow function aspow(a,-1,m).  As such, a future version of this library will remove this function.  That will probably happen once PyPy3 supports Python 3.8.crt(rems,mods)Returns the unique integercinrange(iterprod(mods))such thatc≡x(mody) for (x,y) inzip(rems, mods).  All elements ofmodsmust be pairwise coprime.lcm(a,*r)The least common multiple of any number of values.  Now thatmath.lcmsupports any number of arguments, a future version of this library will replace this function definition withfrom math import lcm.isqrt(n)Greatest integer whose square is ≤n.  Now that Python 3.9 has themath.isqrtfunction, a future version of this library will remove this function definition in favor of the linefrom math import isqrt.introot(n,r=2)For non-negativen, returns the greatest integer ≤ the rth root ofn.  For negativen, returns the least integer ≥ therthroot ofn, orNoneifris even.semiprimegen()Generates the semiprimes.  This is done by filtering the primes out of the output ofpspgen.pspgen()Generates the primes and semiprimes.  This is done using a segmented sieve based on the sieve of Eratosthenes and the fact that these are precisely the numbers not divisible by any smaller semiprimes.almostprimegen(k)Generates thek-almost-primes, which are the numbers that have preciselykprime factors, counted with multiplicity.  This is done by filteringnearlyprimegen(k-1)out of the output ofnearlyprimegen(k).nearlyprimegen(k)Generates the numbers (other than 1) that havekor fewer prime factors, counted with multipicity.  This is done via a segmented sieve based on the sieve of Eratosthenes and the fact that these are precisely the numbers not divisible by any smallerk-almost-primes.ispower(n,r=0)Ifr= 0: Ifnis a perfect power, return a tuple containing the largest integer that, when squares/cubed/etc, yieldsnas the first component and the relevant power as the second component.  Ifnis not a perfect power, returnNone.Ifr> 0: We check whethernis a perfectrthpower; we return itsrthroot if it is andNoneif it isn’t.ilog(x,b)Greatest integerksuch thatbk≤x.fibogen()Generates the Fibonacci numbers, starting with 0 and 1.fibo(n,f={0:0,1:1,2:1})Efficiently extracts thenthFibonacci number, indexed so thatfibo(0)= 0 andfibo(1)=fibo(2)= 1.  The argumentfis used for memoization.  We compute O(log(n)) earlier Fibonaccis along the way.  This is, in the big-O sense, just about as fast as possible.fibomod(n,m,f={0:0,1:1,2:1})Efficiently extracts the nth Fibonacci number modulom, indexed so thatfibo(0)= 0 andfibo(1)==fibo(2)= 1.  The argumentfis used for memoization.  We compute O(log(n)) earlier Fibonaccis along the way.  This is the asymptotically fastest algorithm.lucaschain(n,x0,x1,op1,op2)Algorithm 3.6.7 fromPrime Numbers: A Computational Perspectiveby Crandall & Pomerance (2ndedition): Evaluation of a binary Lucas chain.  To quote their description:For a sequencex0,x1, … with a rule for computingx2jfromxjand a rule for computingx2j+1fromxjandxj+1, this algorithm computes (xn,xn+1) for a given positive integern.  We havenin binary as (n0,n1, …,nb-1) withn0being the low-order bit.  We write the rules as follows:x2j= op1(xj) andx2j+1= op2(xj,xj+1).lucasgen(P,Q):Generates the Lucas U- and V-sequences with parameters (P,Q).lucas(k,P,Q)Efficiently computes thekthterms in the Lucas U- and V-sequences U(P,Q) and V(P,Q).  More explicitly, ifU0, U1, V0, V1= 0, 1, 2,Pand we have the recursionsUn=P· Un-1-Q· Un-2Vn=P· Vn-1-Q· Vn-2then we compute Ukand Vkin O(ln(k)) arithmetic operations.  IfP2≠ 4·Q, then these sequences grow exponentially, so the number of bit operations is anywhere from O(k· ln(k)2· ln(ln(k))) to O(k2) depending on how multiplication is handled.  We recommend using MPZs whenk> 100 or so.  We divide byP2- 4·Qat the end, so we handle separately the case where this is zero.binlinrecgen(P,Q,a,b)The general binary linear recursion.  Exactly likelucasgen, except we only compute one sequence, and we supply the seeds.binlinrec(k,P,Q,a,b)The general binary linear recursion.  Exactly likelucas, except we compute only one sequence, and we supply the seeds.linrecgen(a,b,m=None)The general homogenous linear recursion: we generate in order the sequence defined byxn+1=ak·xn+ak-1·xn-1+ … +a0·xn-k,where the initial values are [x0, …,xk] =b.  Ifmis supplied, then we compute the sequence modulom.  The terms of this sequence usually grow exponentially, so computing a distant term incrementally by plucking it out of this generator takes O(n2) bit operations.  Extractions of distant terms should therefore be done vialinrec, which takes anywhere from O(n· ln(n)2· ln(ln(n))) to O(n2) bit operations depending on how multiplication is handled.linrec(n,a,b,m=None)The general homogeneous linear recursion.  Ifmis supplied, terms are computed modulom.  We use matrix methods to efficiently compute thenthterm of the recursionxn+1=ak·xn+ak-1·xn-1+ … +a0·xn-k,where the initial values are [x0, …,xk] =b.legendre(a,p)Legendre symbol (a|p): 1 ifais a quadratic residue modp, -1 if it isn’t, and 0 ifa≡ 0 (modp).  Not meaningful ifpisn’t prime.jacobi(a,n)The Jacobi symbol (a|n).kronecker(a,n)The Kronecker symbol (a|n).  Note that this is the generalization of the Jacobi symbol,notthe Dirac-delta analogue.sprp(n,b)The strong probable primality test (aka single-round Miller-Rabin).mrab(n,basis)Miller-Rabin probable primality test.miller(n)Miller’s primality test.  If the extended Riemann hypothesis (the one about Dirichlet L-functions) is true, then this test is deterministic.lprp(n,a,b)Lucas probable primality test as described inPrime Numbers: A Computational Perspectiveby Crandall & Pomerance (2ndedition).lucasmod(k,P,Q,m)Efficiently computes thekthterms of Lucas U- and V-sequences modulomwith parameters (P,Q).  Currently just a helper function forslprpandxslprp.  Will be upgraded to full status when the casegcd(D,m)!=1is handled properly.slprp(n,a,b)Strong lucas probable primality test as described on Wikipedia.  Its false positives are a strict subset of those forlprpwith the same parameters.xslprp(n,a)Extra strong Lucas probable primality test as described on Wikipedia.  Its false positives are a strict subset of those forslprp(and thereforelprp) with parameters (a, 1).bpsw(n)The Baille-Pomerance-Selfridge-Wagstaff probable primality test.  Infinitely many false positives are conjectured to exist, but none are known, and the test is known to be deterministic below 264.qfprp(n,a,b)Quadratic Frobenius probable primality test as described inPrime Numbers: A Computational Perspectiveby Crandall & Pomerance (2ndedition).polyaddmodp(a,b,p)Adds two polynomials and reduces their coefficients modp.  Polynomials are written as lists of integers with the constant terms first.  If the high-degree coefficients are zero, those terms will be deleted from the answer so that the highest-degree term is nonzero.  We assume that the inputs also satisfy this property.  The zero polynomial is represented by the empty list.  If one of the input polynomials isNone, we returnNone.polysubmodp(a,b,p)Subtracts the polynomialbfromaand reduces their coefficients modp.  Polynomials are written as lists of integers with the constant terms first.  If the high-degree coefficients are zero, those terms will be deleted from the answer so that the highest-degree term is nonzero.  We assume that the inputs also satisfy this property.  The zero polynomial is represented by the empty list.  If one of the input polynomials isNone, we returnNone.polymulmodp(a,b,p)Multiplies the polynomialsaandband reduces their coefficients modp.  Polynomials are written as lists of integers with the constant terms first.  If the high-degree coefficients are zero, those terms will be deleted from the answer so that the highest-degree term is nonzero.  We assume that the inputs also satisfy this property.  The zero polynomial is represented by the empty list.  If one of the input polynomials isNone, we returnNone.polydivmodmodp(a,b,p)Divides the polynomialaby the polynomialband returns the quotient and remainder.  The coefficients are interpreted modp.  Polynomials are written as lists of integers with the constant terms first.  If the high-degree coefficients are zero, those terms will be deleted from the answer so that the highest-degree term is nonzero.  We assume that the inputs also satisfy this property.  The zero polynomial is represented by the empty list.  If one of the input polynomials isNone, we returnNone.  The result is not guaranteed to exist; in such cases we return(None, None).gcmd(f,g,p)Computes the greatest common monic divisor of the polynomialsfandg.  The coefficients are interpreted modp.  Polynomials are written as lists of integers with the constant terms first.  If the high-degree coefficients are zero, those terms will be deleted from the answer so that the highest-degree term is nonzero.  We assume that the inputs also satisfy this property.  The zero polynomial is represented by the empty list.  If one of the input polynomials isNone, or if both input polynomials are[], we returnNone.  The result is not guaranteed to exist; in such cases, we returnNone.  Coded after algorithm 2.2.1 fromPrime Numbers: A Computational Perspectiveby Crandall & Pomerance (2ndedition).polypowmodpmodpoly(a,e,p,f)Computes the remainder when the polynomialais raised to theethpower and reduced modulof.  The coefficients are interpreted modp.  Polynomials are written as lists of integers with the constant terms first.  If the high-degree coefficients are zero, those terms will be deleted from the answer so that the highest-degree term is nonzero.  We assume that the inputs also satisfy this property.  The zero polynomial is represented by the empty list.  If one of the input polynomials isNone, or iff == [], we returnNone.  The answer is not guaranteed to exist.  In such cases, we returnNone.frobenius_prp(n,poly,strong=False)Grantham’s general Frobenius probable primality test, in both the strong and weak versions, as described inhis paper introducing the test.isprime(n,tb=(3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59))The workhorse primality test.  It is a BPSW primality test variant: we use the strong Lucas PRP test and preface the computation with trial division for speed.  No composites are known to pass the test, though it is suspected that infinitely many will do so.  There are definitely no such errors below 264.  This function is mainly a streamlined version ofbpsw.isprimepower(n)Determines whethernis of the formpefor some prime numberpand positive integere, and returns (p,e) if so.isprime_mersenne(p)The Lucas-Lehmer test.  Deterministically and efficiently checks whether the Mersenne number 2p-1 is prime.nextprime(n,primetest=isprime)Smallest prime strictly greater thann.prevprime(n,primetest=isprime)Largest prime strictly less thann, orNoneif no such prime exists.randprime(digits,base=10,primetest=isprime)Returns a random prime with the specified number of digits when rendered in the specified base.randomfactored(n,primetest=isprime)Efficiently generates an integer selected uniformly from the range [1,n] with its factorization.  Uses Adam Kalai’s algorithm, which uses in the average case O(log(n)2) primality tests.  When called with the default primality test, this then uses O(log(n)3) arithmetic operations, which in turn results in just over O(log(n)4) to O(log(n)5) bit operations, depending on how multiplication is handled.sqrtmod_prime(a,p)Findsxsuch thatx2≡a(modp).  We assume thatpis a prime andais a quadratic residue modulop.  If any of these conditions is false, then the return value is meaningless.cbrtmod_prime(a,p)Returns in a sorted list all cube roots of a mod p.  There are a bunch of easily-computed special formulae for various cases withp!= 1 (mod 9); we do those first, and then ifp== 1 (mod 9) we use Algorithm 4.2 inTaking Cube Roots in Zmby Padro and Saez, which is essentially a variation on the Tonelli-Shanks algorithm for modular square roots.pollardrho_brent(n)Factors integers using Brent’s variation of Pollard’s rho algorithm.  Ifnis prime, we immediately returnn; if not, we keep chugging until a nontrivial factor is found.pollard_pm1(n,B1=100,B2=1000)Integer factoring function.  Uses Pollard’s p-1 algorithm.  Note that this is only efficient if the number to be factored has a prime factorpsuch thatp-1’s largest prime factor is “small”.mlucas(v,a,n)Helper function forwilliams_pp1.  Multiplies along a Lucas sequence modulon.williams_pp1(n)Integer factoring function.  Uses Williams’ p+1 algorithm, single-stage variant.  Note that this is only efficient when the number to be factored has a prime factorpsuch thatp+1’s largest prime factor is “small”.ecadd(p1,p2,p0,n)Helper function forecm.  Adds two points on a Montgomery curve modulon.ecdub(p,A,n)Helper function forecm.  Doubles a point on a Montgomery curve modulon.ecmul(m,p,A,n)Helper function forecm.  Multiplies a point on Montgomery curve by an integer modulon.secm(n,B1,B2,seed)Seeded elliptic curve factoring using the two-phase algorithm on Montgomery curves.  Helper function forecm.  Returns a possibly-trivial divisor ofngiven two bounds and a seed.ecmparams(n)Generator of parameters to use forsecm.ecm(n,paramseq=ecmparams,nprocs=1)Integer factoring via elliptic curves using the two-phase algorithm on Montgomery curves, and optionally uses multiple processes.  This is a shell function that repeatedly callssecmusing parameters provided byecmparams; the actual factoring work is done there.  Multiprocessing incurs relatively significant overhead, so whennprocs==1(default), we don’t call the multiprocessing functions.siqs(n)Factors an integer via the self-initializing quadratic sieve.  Most of this function is copied verbatim fromhttps://github.com/skollmann/PyFactorise.multifactor(n,methods)Integer factoring function.  Uses several methods in parallel.  Waits for one of them to return, kills the rest, and reports.primefac(n,trial=1000,rho=42000,primetest=isprime,methods=(pollardrho_brent,))The workhorse integer factorizer.  Generates the prime factors of the input.  Factors that appearxtimes are yieldedxtimes.factorint(n,trial=1000,rho=42000,primetest=isprime,methods=(pollardrho_brent,))Compiles the output ofprimefacinto a dictionary with primes as keys and multiplicities as values.factorsieve(stop)Uses a sieve to compute the factorizations of all whole numbers strictly less than the input.  This uses a lot of memory; if you aren’t after the factors directly, it’s usually better to write a dedicated function for whatever it is that you actually want.divisors(n)Generates all natural numbers that evenly dividen.  The output is not necessarily sorted.divisors_factored(n)Generates the divisors ofn, written as their prime factorizations in factorint format.divcount(n)Counts the number of divisors ofn.divsigma(n,x=1)Sum of divisors of a natural number, raised to thexthpower.  The conventional notation for this in mathematical literature is σx(n), hence the name of this function.divcountsieve(stop)Uses a sieve to compute the number of divisors of all whole numbers strictly less than the input.totient(n,k=1)Jordan’s totient function: the number ofk-tuples of positive integers all ≤nthat form a coprime (k+1)-tuple together withn.  Whenk= 1, this is Euler’s totient: the number of numbers less than a number that are relatively prime to that number.totientsieve(n)Uses a sieve to compute the totients up to (and including)n.totientsum(n)Computessum(totient(n) for n in range(1, n+1))efficiently.mobius(n)The Möbius function ofn: 1 ifnis squarefree with an even number of prime factors, -1 ifnis squarefree with an odd number of prime factors, and 0 ifnhas a repeated prime factor.mobiussieve(stop)Uses a sieve to compute the Möbius function of all whole numbers strictly less than the input.liouville(n)The Liouville lambda function ofn: the strongly multiplicative function that is -1 on the primes.polyroots_prime(g,p,sqfr=False)Generates with some efficiency and without multiplicity the zeros of a polynomial modulo a prime.  Coded after algorithm 2.3.10 fromPrime Numbers: A Computational Perspectiveby Crandall & Pomerance (2ndedition), which is essentially Cantor-Zassenhaus.hensel(f,p,k,given=None)Uses Hensel lifting to generate with some efficiency all zeros of a polynomial modulo a prime power.sqrtmod(a,n)Computes all square roots ofamodulonand returns them in a sorted list.polyrootsmod(pol,n)Computes the zeros of a polynomial modulo an integer.  We do this by factoring the modulus, solving modulo the prime power factors, and putting the results back together via the Chinese Remainder Theorem.PQa(P,Q,D)Generates some sequences related to simple continued fractions of certain quadratic surds.  A helper function forpell.  LetP,Q, andDbe integers such thatQ≠ 0,D> 0 is a nonsquare, andP2≡D(modQ). We yield a sequence of tuples (Bi,Gi,Pi,Qi) whereiis an index counting up from 0,x= (P+√D)/Q= [a0;a1,a2, …], (Pi+√D))/Qiis theithcomplete quotient ofx, andBiis the denominator of theithconvergent tox.  For full details, seehttps://web.archive.org/web/20180831180333/http://www.jpr2718.org/pell.pdf.pell(D,N)This function solves the generalized Pell equation: we find all non-negative integers (x,y) such thatx2-D·y2=N.  We have several cases:Case 1:N= 0.  We solvex2=D·y2.  (0,0) is always a solution.Case 1a: IfDis a nonsquare, then there are no further solutions.Case 1b: IfDis a square, then there are infinitely many solutions, parametrized by (t·√D,t).Case 2:N≠ 0 =D.  We solvex2=N.Case 2a: IfNis a nonsquare, then there are no solutions.Case 2b: IfNis a square, then there are infinitely many solutions, parametrized by (√N,t).Case 3:N≠ 0 >D.  We solvex2+ |D| ·y2=N.  The number of solutions will be finite.Case 4:N≠ 0 <D.  We find lattice points on a hyperbola.Case 4a: IfDis a square, then the number of solutions will be at most finite.  This case is solved by factoring.Case 4b: IfDis a nonsquare, then we run the PQa/LMM algorithms: we produce a set of primitive solutions; if this set is empty, there are no solutions; if this set has members, an ininite set of solutions can be produced by repeatedly composing them with the fundamental solution ofx2-D·y2= 1.References:https://web.archive.org/web/20180831180333/https://www.jpr2718.org/pell.pdfhttp://www.offtonic.com/blog/?p=12http://www.offtonic.com/blog/?p=18Input:D,N– integersOutput:A 3-tuple.If the number of solutions is finite, it is(None, z, None), wherezis the sorted list of all solutions.If the number of solutions is infinite and the equation is degenerate, it’s(gen, None, None), wheregenyields all solutions.If the number of solutions if infinite and the equation is nondegenerate, it is(gen, z, f), wherezis the set of primitive solutions, represented as a sorted list, andfis the fundamental solution — i.e.,fis the primitive solution ofx2-D·y2= 1.Note that we can check the infinitude of solutions by callingbool(pell(D,N)[0]).simplepell(D,bail=inf)Generates the positive solutions ofx2-D·y2= 1.  We use some optimizations specific to this case of the Pell equation that makes this more efficient than callingpell(D,1)[0].  Note that this function is not equivalent to callingpell(D,1)[0]:pellis concerned with the general equation, which may or may not have trivial solutions, and as such yields all non-negative solutions, whereas this function is concerned only with the simple Pell equation, which always has an infinite family of positive solutions generated from a single primitive solution and always has the trivial solution (1,0).We yield only those solutions withx≤bail.carmichael(n)The Carmichael lambda function: the smallest positive integermsuch thatam≡ 1 (modn) for allasuch that gcd(a,n) = 1.  Also called the reduced totient or least universal exponent.multord(b,n)Computes the multiplicative order ofbmodulon; i.e., finds the smallestksuch thatbk≡ 1 (modn).pythags_by_perimeter(p)Generates all Pythagorean triples of a given perimeter by examining the perimeter’s factors.collatz(n)Generates the Collatz sequence initiated byn.  Stops after yielding 1.sqrtcfrac(n)Computes the simple continued fraction for √n.  We return the answer as(isqrt(n),[a,b,c,...,d]), where[a,b,c,...,d]is the minimal reptend.convergents(a)Generates the convergents of a simple continued fraction.contfrac_rat(n,d)Returns the simple continued fraction of the rational numbern/d.quadratic_scf(P,Q,D)Computes the simple continued fraction of the expression (P+ sqrt(D)) /Q, for any integersP,Q, andDwithD≥ 0 ≠Q.  Note thatDcan be a square or a nonsquare.ngonal(x,n)Returns thexthn-gonal number.  Indexing begins with 1 so thatngonal(1, n)= 1 for all applicablen.is_ngonal(p,n)Checks whetherpis ann-gonal number.partitions(n,parts=[1])Computes with some semblance of efficiency the number of additive partitions of an integer.  Thepartsargument is for memoization.partgen(n)Generates partitions of integers in ascending order via an iterative algorithm.  It is the fastest known algorithm as of June 2014.partconj(p)Computes the conjugate of a partition.farey(n)Generates the Farey sequence of maximum denominatorn.  Includes 0/1 and 1/1.fareyneighbors(n,p,q)Returns the neighbors ofp/qin the Farey sequence of maximum denominatorn.ispractical(n)Tests whethernis a practical number – i.e., whether every integer from 1 throughn(inclusive) can be written as a sum of divisors ofn.  These are also called panarithmic numbers.hamming(ps,*ps2)Generates allps-smooth numbers, wherepsis a list of primes.arithmeticderivative(n)The arithmetic derivative ofn: ifnis prime, thenn’ = 1; if -2 <n< 2, thenn’ = 0; ifn< 0, thenn’ = -(-n)’; and (ab)’ =a’·b+b’·a.perfectpowers()Generates the sequence of perfect powers without multiplicity.sqfrgen(ps)Generates the squarefree products of the elements ofps.sqfrgenb(ps,b,k=0,m=1)Generates the squarefree products of elements ofps.  Does not yield anything >b.  For best performance,psshould be sorted in decreasing order.stormer(ps,*ps2,abc=None)Størmer’s theorem asserts that for any given setpsof prime numbers, there are only finitely many pairs of consecutive integers that are bothps-smooth; the theorem also gives an effective algorithm for finding them.  We implement Lenstra’s improvement to this theorem.Theabcargument indicates that we are to assume an effective abc conjecture of the formc<abc[0]· rad(a·b·c)abc[1].  This enables major speedups.  IfabcisNone, then we make no such assumptions.quadintroots(a,b,c)Given integersa,b, andc, we return in a tuple all distinct integersxsuch thata·x2+b·x+c= 0.  This is primarily a helper function forcubicintrootsgivenandcubicintroots.cubicintrootsgiven(a,b,c,d,r)Given integersa,b,c,d, andrsuch thata·r3+b·r2+c·r+d= 0, we find the cubic’s other two roots and return in a tuple all distinct integer roots (includingr).  This is primarily a helper function forcubicintroots.cubicintroots(a,b,c,d)Given integersa,b,c,d, we return in a tuple all distinct integer roots ofa·x3+b·x2+c·x+d.  This is primarily a helper function forisprime_nm1.isprime_nm1(n,fac=None)Then-1 primality test: given an odd integern> 214 and a fully-factored integerFsuch thatFdividesn-1 andF>n0.3, we quickly determine without error whethernis prime.  If the provided (partial) factorization ofn-1 is insufficient, we compute the factorization ourselves.isprime_np1(n,fac=None)Then+1 primality test: given an odd integern> 214 and a fully-factored integerFsuch thatFdividesn+1 andF>n0.3, we quickly determine without error whethernis prime.  If the provided (partial) factorization ofn+1 is insufficient, we compute the factorization ourselves.mulparts(n,r=None,nfac=None)Generates all orderedr-tuples of positive integers whose product isn.  IfrisNone, then we generate all such tuples (regardless of size) that do not contain 1.dirconv(f,g,ffac=False,gfac=False)This returns a function that is the Dirichlet convolution offandg.  When called with the keyword arguments at their default values, this is equivalent to the expressionlambda n: sum(f(d) *g(n//d)for d in divisors(n)).  Ifforgneeds to factor its argument, such asf == totientorg == mobiusor something like that, then that lambda expression calls the factorizer a lot more than it needs to — we’re already factoringn, so instead of feeding those functions the integer forms ofn’s factors, we can instead passffac=Trueorgfac=Truewhendirconvis called and we will calldivisors_factored(n)instead and feed those factored divisors intoforgas appropriate.  This optimization becomes more noticeable as the factoring becomes more difficult.dirichletinverse(f)Computes the Dirichlet inverse of the input functionf.  Mathematically, functionsfsuch thatf(1) = 0 have no Dirichlet inverses due to a division by zero.  This is reflected in this implementation by raising aZeroDivisionErrorwhen attempting to evaluatedirichletinverse(f)(n)for any suchfand anyn.  Iff(1) is neither 1 nor -1, thendirichletinverse(f)will returnFractionobjects (as imported from thefractionsmodule).dirichletroot(f,r,val1)Computes therthDirichlet root of the input functionfwhose value at 1 isval1.  More precisely, letfbe a function on the positive integers, letrbe a positive integer, and letval1r=f(1).  Then we return the unique functiongsuch thatf=g*g* … *g, wheregappearsrtimes and * represents Dirichlet convolution.  The values returned will beFractionobjects (as imported from thefractionsmodule).determinant(M)Computes the determinant of a matrix via the Schur determinant identity.discriminant(coefs)Computes the discriminant of a polynomial.  The input list is ordered from lowest degree to highest — i.e.,coefs[k]is the coefficient of thexkterm.  For low-degree polynomials, explicit formulae are used; for degrees 5 and higher, we compute it by taking the determinant (using this package’sdeterminantfunction) of the Sylvester matrix of the input and its derivative.  This in turn is calculated by the Schur determinant identity.  Note that this has the effect of setting the discriminant of a linear polynomial to 1 (which is conventional) and that of a constant to 0.egypt_short(n,d,terms=0,minden=1)Generates all shortest Egyptian fractions forn/dusing at least the indicated number of terms and whose denominators are all ≥minden.  No algorithm is known for this problem that significantly improves upon brute force, so this can take impractically long times on even modest-seeming inputs.egypt_greedy(n,d)The greedy algorithm for Egyptian fraction expansion; also called the Fibonacci-Sylvester algorithm.DependenciesThis package imports items frommultiprocessing,itertools,fractions,random,math, andheapq.  These are all in the Python standard library.We attempt to importmpzfromgmpy2, but this is purely for efficiency: if this import fails, we simply setmpz = int.