Package: pyfac
For further updates, see theprimefacpackage.PyFac version 1.0.0This is a module and command-line utility for factoring integers.  As a module, we provide a primality test, several functions for extracting a non-trivial factor of an integer, and a generator that yields all of a number’s prime factors (with multiplicity).  As a command-line utility, this project aims to replace GNU’sfactorcommand with a more versatile utility — in particular, this utility can operate on arbitrarily large numbers, uses multiple cores in parallel, uses better algorithms, handles input in reverse Polish notation, and can be tweaked via command-line flags.  Specifically,GNU’sfactorcommand won’t factor anything greater than 2127-1.  PyFac handles arbitrarily large integers.  If available, gmpy or gmpy2 is imported, with the latter taking precedence over the former.GNU’sfactorcommand uses Pollard’s rho algorithm.  While this extracts small factors quickly, large factors take a while to find.  PyFac uses, among other things, the elliptic curve method, which is far more efficient at extracting large factors.GNU’sfactorcommand is a single-threaded application.  PyFac uses by default five threads to take advantage of the multiple cores typically available on modern machines.  Each of these threads uses a different algorithm to factor the number:One thread runs Brent’s variation on Pollard’s rho algorithm.  This is good for extracting smallish factors quickly.One thread runs the two-stage version of Pollard’sp-1 method.  This is good at finding factorspfor whichp-1 is a product of small primes.One thread runs Williams’p+1 method.  This is good at finding factorspfor whichp+1 is a product of small primes.One thread runs the elliptic curve method.  This is a bit slower than Pollard’s rho algorithm when the factors extracted are small, but it has significantly better performance on difficult factors.One thread runs the multiple-polynomial quadratic sieve.  This is the best algorithm for factoring “hard” numbers short of the horrifically complex general number field sieve.  However, it’s (relatively speaking) more than a little slow when the numbers are small, and the time it takes depends only on the size of the number being factored rather than the size of the factors being extracted as with Pollard’s rho algorithm and the elliptic curve method, so we use the preceding algorithms to handle those.We also extend the utility by interpreting the command-line arguments as an expression in reverse Polish notation and factoring the numbers remaining on the evaluation stack when interpretation is complete.  For example, the command:python -m pyfac 24 ! 1 - 38 ! 1 +will factor the numbers 24! - 1 = 620448401733239439359999 and 38! + 1 = 523022617466601111760007224100074291200000001.Module UsageThe primary functions areisprimeandprimefac, but we define a number of helper functions along the way.gcd(a,b)Computes the greatest common divisor of the integersaandb.isqrt(n)Computes the greatest integer whose square does not exceed the non-negative integern.introot(n,r=2)For non-negativen, returns the greatest integer less than or equal to therthroot ofn.For negativen, returns the least integer greater than or equal to therthroot ofn, orNoneifris even.primegen()Non-terminating generator.  Yields the prime numbers.  It amounts to a recursive Sieve of Eratosthenes.  Memory usage is on the order of the square root of the most-recently-yielded prime.  Seethis Programming Praxis postfor more about the algorithm.primes(n)Returns a list of the primes strictly less thann.listprod(l)Returns the product of the elements ofl, which can be any iterable (but should obviously terminate; e.g.,listprod(primegen())would be a bad idea).nextprime(n)Determines, with some semblance of efficiency, the least prime number strictly greater thann.sprp(n,a,s=None,d=None)Checksnfor primality using the Strong Probable Primality Test to basea.  If present,sanddshould be the first and second items, respectively, of the tuple returned by the functionpfactor(n).  We use this as a helper function forisprime.pfactor(n)Helper function forsprp.  Returns the tuple(x,y)wheren - 1 == (2 ** x) * yandyis odd.  We have this bit separated out so that we don’t waste time recomputingsanddfor each base when we want to checknagainst multiple bases.jacobi(a,p)Computes the Jacobi symbol(a|p), wherepis a positive odd number.  This is used inisprime.chain(n,u1,v1,u2,v2,d,q,m)Helper function forisprime.isprime(n,tb=(3,5,7,11),eb=(2,),mrb=())The main primality test.  It’s an implementation of the BPSW test (Baillie-Pomerance-Selfridge-Wagstaff) with some prefiltes for speed and is deterministic for all numbers less than 264— in fact, while infinitely many false positives are conjectured to exist, no false positives are currently known.  The prefilters consist of trial division against 2 and the elements of the tupletb, checking whethernis square, and Euler’s primality test to the bases in the tupleeb.  If the number is less than 3825123056546413051, we use the Miller-Rabin test on a set of bases for which the test is known to be deterministic over this range.ilog(x,b)Returns the greatest integerlsuch thatb**l<= x.ispower(n)Returns the largest integer that, when squared/cubed/etc, yieldsn, or 0 if no such integer exists.  Note that the power to which this number is raised will be prime.pollardRho_brent(n)Brent’s improvement on Pollard’s rho algorithm.  Returnsnifnis prime; otherwise, we keep chugging until we find a factor ofnstrictly between1andn.pollard_pm1(n,B1=100,B2=1000)Pollard’sp+1 algorithm, two-phase version.  Returnsnifnis prime; otherwise, we keep chugging until we find a factor ofnstrictly between1andn.mlucas(v,a,n)Helper function forwilliams_pp1.  Multiplies along a Lucas sequence modulon.williams_pp1(n)Williams’p+1 algorithm.  Returnsnifnis prime; otherwise, we keep chugging until we find a factor ofnstrictly between1andn.ecadd(p1,p2,p0,n)Helper function forecm.  Adds two pointsp1andp2given pointP0 =P1-P2modulon.ecdub(p,A,n)Helper function forecm.  Doubles pointponAmodulon.ecmul(m,p,A,n)Helper function forecm.  Multiplies pointpbymon curveAmodulon.ecm(n,B1=10,B2=20)Factorsnusing the elliptic curve method, using Montgomery curves and an algorithm analogous to the two-phase variant of Pollard’sp-1 method.  Returnsnifnis prime; otherwise, we keep chugging until we find a factor ofnstrictly between1andn.  For more details seethesetwoProgramming Praxis posts.legendre(a,p),legendre1(a,p),legendre2(a,p)Functions to comptue the Legendre symbol(a|p).  The return value isn’t meaningful ifpis composite.  We have three functions for this becaues of the details of the corresponding function ingmpyand how it’s accessed.mod_sqrt(n,p)Computes a square root ofnmodulo the prime numberp.  The return value is not meaningful ifnhas no square root modulopor ifpis composite.modinv(a,m)Computes a multiplicative inverse ofamodulom.  The return value is not meaningful ifgcd(a,m) != 1.mpqs(n)Factorsnusing the multiple polynomial quadratic sieve.  Returnsnifnis prime; otherwise, we keep chugging until we find a factor ofnstrictly between1andn.  This function was copied mostly verbatim fromthis stackexchange post.multifactor(n,methods=(pollardRho_brent,pollard_pm1,williams_pp1,ecm,mpqs),verbose=False)Runs several factoring algorithms onnsimultaneously by loading them into their own threads via themultiprocessingmodule.  When one function returns, everything is killed off and that value gets returned.primefac(n,trial_limit=1000,rho_rounds=42000,verbose=False,methods=(pollardRho_brent,pollard_pm1,williams_pp1,ecm,mpqs))Generator.  Yields the prime factors ofn, with multiplicity.rpn(instr)Evaluates the stringinstras an expression in reverse Polish notation.DependenciesThis package imports items frommultiprocessing,random,itertools, andmath.  These are all in the Python standard library.We attempt to import items fromgmpy2(or, failing that,gmpy), but these packages are not necessary: the GMPY functions that would be imported are implemented natively if the import fails.Command-Line Usagepython-mpyfac[-vs][-v|--verbose][-s|--summary][-t=NUM][-r=NUM][-m=[prb][,p-1][,p+1][,ecm][,mpqs]]rpnrpnis an expression in revese Polish notation and is evaluated using integer arithmetic.  Each number that remains on the stack after evaluation is then factored.-tsets the trial division limit; the default value is 1000.  Use-t=infto use trial division exclusively.-ris the number of rounds of Pollard’s rho algorithm to try before calling a factor “difficult”.  The default value is 42,000.  Use-r=infto use Pollard’s rho exclusively once the trial division is completed.If verbosity is invoked, we indicate in the output which algorithm produced which factors during the multifactor phase.If the-s(or--summary) flag is absent, then output is identical to the output of the GNUfactorcommand, except possibly for the order of the factors and, if verbosity has been turned on, the annotations indicating which algorithm produced which factors.If the-s(or--summary) flag is present, then output is modified by adding a single newline between each item’s output, before the first item, and after the last item.  Each item’s output is also modified by printing a second line of data summarizing the results by describing the number of decimal digits in the input, the number of decimal digits in each prime factor, and the factors’ multiplicities.  For example:>>> user@computer:~$ python -m pyfac  -sv   24 ! 1 -   7 !
>>>
>>> 620448401733239439359999: ecm 991459181683 625793187653
>>> Z24  =  P12 x P12  =  625793187653 x 991459181683
>>>
>>> 5040: 2 2 2 2 3 3 5 7
>>> Z4  =  P1^4 x P1^2 x P1 x P1  =  2^4 x 3^2 x 5 x 7
>>>
>>> user@computer:~$Note that the primes in the summary lines are listed in strictly-increasing order, regardless of the order in which they were found.The-vand-sflags may be combined into a single flag in either order — i.e., into-vsor-sv.The-m=flag controls the functions used during themultifactorphase.  The options areprb,p-1,p+1,ecm, andmpqs, representing Pollard’s rho, Pollard’sp-1, Williams’p+1, the elliptic curve method, and the multiple polynomial quadratic sieve, respectively.  The options must be separated by commas.  The options can be repeated: ifprbis listed twice, for example, thenmultifactorwill run two instances ofpollardRho_brentsimultaneously.  In the case ofprbandecm, this decreases the expectation value of the time to find a factor, whereas the other three algorithms (p-1,p+1, and MPQS) have no randomized component so that running duplicate instances of these three algorithms confers no benefit.  We therefore ignore repeated listings of the latter three methods: for example, callingpython-mpyfac-m=prb,prb,ecm,ecm,ecm,mpqs,mpqs38!1+will run during the multifactor phase two instances of Pollard’s rho, three instances of the elliptic curve method, and one instance of the MQPS.  Invoking more methods than you have cores available is unlikely to confer any benefit.RPNThe acceptable binary operators are+,-,*,/,%, and**.  They all have the same meaning as they do in Python source code — i.e., they are addition, subtraction, multiplication, integer division, remainder, and exponentiation, respectively.  The acceptable unary operators are!and#.  They are the factorial and primorial, respectively.  To avoid triggering the shell’s special characters, there are three aliases:xfor*,xxfor**, andp!for#.  You may also enclose the RPN expression in quotes if this helps avoid interpretation problems with your shell.