!"#$%&'()*+,- . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ?@ A B C D E FGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ "(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> Provisionalportable Safe-Inferred n gives (for n > 0?) an approximation of the number of primes not exceeding n'. The approximation is fairly good for n large enough. The number of primes should be slightly overestimated (so it is suitable for allocation of storage) and is never underestimated for  n <= 10^12. n gives (for n > 0Q) an approximation to the n-th prime. The approximation is fairly good for n large enough. Dual to <, this estimate should err on the low side (and does for  n < 10^12).(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions) Safe-Inferred k calculates the k-th Fibonacci number in O( log (abs k)1) steps. The index may be negative. This is efficient for calculating single Fibonacci numbers (with large index), but for computing many Fibonacci numbers in close proximity, it is better to use the simple addition formula starting from an appropriate pair of successive Fibonacci numbers. k returns the pair (F(k), F(k+1)) of the k-th Fibonacci number and its successor, thus it can be used to calculate the Fibonacci numbers from some index on without needing to compute the previous. The pair is efficiently calculated in O( log (abs k)#) steps. The index may be negative. k computes the k%-th Lucas number. Very similar to . k computes the pair (L(k), L(k+1)) of the k7-th Lucas number and its successor. Very similar to . p q k calculates the quadruple (U(k), U(k+1), V(k), V(k+1)) where U(i)- is the Lucas sequence of the first kind and V(i)= the Lucas sequence of the second kind for the parameters p and q, where  p^2-4q /= 04. Both sequences satisfy the recurrence relation A(j+2) = p*A(j+1) - q*A(j), the starting values are U(0) = 0, U(1) = 1 and V(0) = 2, V(1) = p[. The Fibonacci numbers form the Lucas sequence of the first kind for the parameters  p = 1, q = -1 and the Lucas numbers form the Lucas sequence of the second kind for these parameters. Here, the index must be non-negative, since the terms of the sequence for negative indices are in general not integers.(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NonefA list of primes. The sieve does not handle overflow, hence for bounded types, garbage occurs near ,. If primes that large are requested, use    $  (<=  )  Pinstead. Checking for overflow would be slower. The sieve is specialised for ,  and A, since these are the most commonly used. For the fixed-width Int or Word types, sieving at one of the specialised types and converting is faster. To ensure sharing of the list of primes, bind it to a monomorphic variable, to make sure that it is not shared, use  with different arguments. n generates the list of primes >= nK. The remarks about overflow and performance in the documentation of  apply here too.(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None;Remove factors of 2 and count them. If  n = 2^k*m with m odd, the result is (k, m) . Precondition: argument not 0 (not checked).Specialised version for <. Precondition: argument strictly positive (not checked).Specialised version for 2. Precondition: argument nonzero (not checked).Specialised version for 2. Precondition: argument nonzero (not checked).Remove factors of 2. If  n = 2^k*m with m odd, the result is m . Precondition: argument not 0 (not checked).Specialised version for 2. Precondition: argument nonzero (not checked).Specialised version for 2. Precondition: argument nonzero (not checked).Specialised version for 2. Precondition: argument nonzero (not checked).LShift argument right until the result is odd. Precondition: argument not 0, not checked.Like ., but count the number of places to shift too.Number of 1-bits in a .Number of 1-bits in a .Number of 1-bits in an .Number of trailing zeros in a  , wrong for 0. (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None; Greatest common divisor of two ,s, calculated with the binary gcd algorithm. Test whether two 9s are coprime, using an abbreviated binary gcd algorithm. Greatest common divisor of two ,s, calculated with the binary gcd algorithm. Test whether two 9s are coprime, using an abbreviated binary gcd algorithm. Greatest common divisor of two ,s, calculated with the binary gcd algorithm.Test whether two s are coprime.Greatest common divisor of two ,s, calculated with the binary gcd algorithm.Test whether two s are coprime.     (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None;Calculate the greatest common divisor using the binary gcd algorithm. Depending on type and hardware, that can be considerably faster than ) but it may also be significantly slower.$There are specialised functions for  and $ and rewrite rules for those and IntN and WordN, N <= 64^, to use the specialised variants. These types are worth benchmarking, others probably not.It is very slow for \ (and probably every type except the abovementioned), I recommend not using it for those.ORelies on twos complement or sign and magnitude representaion for signed types.dCalculate the greatest common divisor of two numbers and coefficients for the linear combination. Satisfies: Ccase extendedGCD a b of (d, u, v) -> u*a + v*b == d d == gcd a band, for signed types, 9 abs u < abs b || abs b <= 1 abs v < abs a || abs a <= 1(except if one of a and b is  of a signed type).uTest whether two numbers are coprime using an abbreviated binary gcd algorithm. A little bit faster than checking binaryGCD a b == 1B if one of the arguments is even, much faster if both are even.!The remarks about performance at K apply here too, use this function only at the types with rewrite rules.ORelies on twos complement or sign and magnitude representaion for signed types.(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None-Invert a number relative to a modulus. If number and modulus are coprime, the result is  Just inverse where L (number * inverse) `mod` (abs modulus) == 1 0 <= inverse < abs modulusunless  modulus == 0 and abs number == 1!, in which case the result is  Just number. If gcd number modulus > 1, the result is Nothing.gJacobi symbol of two numbers. The "denominator" must be odd and positive, this condition is checked.=If both numbers have a common prime factor, the result is 0, otherwise it is 1.LJacobi symbol of two numbers without validity check of the "denominator".Modular power. powerMod base exponent modulus calculates (base ^ exponent) `mod` modulus+ by repeated squaring and reduction. If  exponent < 0 and base is invertible modulo modulus, $(inverse ^ |exponent|) `mod` modulusj is calculated. This function does some input checking and sanitation before calling the unsafe worker.sModular power worker without input checking. Assumes all arguments strictly positive and modulus greater than 1.Specialised version of  for T exponents. Reduces the number of shifts of the exponent since shifting large `s is expensive. Call this function directly if you don't want or can't rely on rewrite rules.^Specialised worker without input checks. Makes the same assumptions as the general version .sqrtModP n prime% calculates a modular square root of n modulo prime( if that exists. The second argument must be a (positive) prime, otherwise the computation may not terminate and if it does, may yield a wrong result. The precondition is not checked.If prime is a prime and n a quadratic residue modulo prime, the result is Just r where r^2 "a n (mod prime), if n- is a quadratic nonresidue, the result is Nothing.sqrtModPList n prime* computes the list of all square roots of n modulo prime. prime must/ be a (positive) prime. The precondition is not checked.sqrtModP' square prime finds a square root of square modulo prime. prime must be a (positive) prime, and sqaure must" be a quadratic residue modulo prime, i.e. 'jacobi square prime == 1. The precondition is not checked.tonelliShanks square prime calculates a square root of square modulo prime, where prime is a prime of the form 4*k + 1 and square is a quadratic residue modulo primeQ, using the Tonelli-Shanks algorithm. No checks on the input are performed.sqrtModPP n (prime,expo) calculates a square root of n modulo  prime^expo if one exists. prime must be a (positive) prime. expo must be positive, n must be coprime to prime sqrtModF n primePowers calculates a square root of n modulo $product [p^k | (p,k) <- primePowers]. if one exists and all primes are distinct.!sqrtModFList n primePowers calculates all square roots of n modulo $product [p^k | (p,k) <- primePowers] if all primes are distinct."sqrtModPPList n (prime,expo)/ calculates the list of all square roots of n modulo  prime^expo . The same restriction as in  applies to the arguments.# Given a list [(r_1,m_1), ..., (r_n,m_n)] of (residue,modulus) pairs, chineseRemainder; calculates the solution to the simultaneous congruences  r "a r_k (mod m_k) ]if all moduli are pairwise coprime. If not all moduli are pairwise coprime, the result is Nothing, regardless of whether a solution exists.$%chineseRemainder2 (r_1,m_1) (r_2,m_2) calculates the solution of  r "a r_k (mod m_k)if m_1 and m_2 are coprime.  !"#$    !"#$#" !$  !"#$   (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None;(c) 2011-2014 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None;% Power of an / by the left-to-right repeated squaring algorithm. This needs two multiplications in each step while the right-to-left algorithm needs only one multiplication for 0-bits, but here the two factors always have approximately the same size, which on average gains a bit when the result is large.For small results, it is unlikely to be any faster than '(^)', quite possibly slower (though the difference shouldn't be large), and for exponents with few bits set, the same holds. But for exponents with many bits set, the speedup can be significant.Warning:~ No check for the negativity of the exponent is performed, a negative exponent is interpreted as a large positive exponent.&Same as %, but for exponents of type .A raw version of testBit for .%&%&%&%&(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneTotient of a prime power.'7Calculate the totient from the canonical factorisation.({Calculate the Carmichael function from the factorisation. Requires that the list of prime factors is strictly ascending.)MThe set of divisors, efficiently calculated from the canonical factorisation.*PThe number of divisors, efficiently calculated from the canonical factorisation.+QThe sum of all divisors, efficiently calculated from the canonical factorisation.,xThe sum of the powers (with fixed exponent) of all divisors, efficiently calculated from the canonical factorisation. '()*+,'()*+, '()*+, (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None3;-:Calculate the integer square root of a nonnegative number n", that is, the largest integer r with r*r <= n'. Throws an error on negative input..:Calculate the integer square root of a nonnegative number n", that is, the largest integer r with r*r <= n. The precondition n >= 0 is not checked./Returns % if the argument is not a square,  r if r*r == n and r >= 0<. Avoids the expensive calculation of the square root if n is recognized as a non-square before, prevents repeated calculation of the square root if only the roots of perfect squares are needed. Checks for negativity and 2.0XTest whether the argument is a square. After a number is found to be positive, first 2@ is checked, if it is, the integer square root is calculated.1.Test whether the input (a nonnegative number) n is a square. The same as 0W, but without the negativity test. Faster if many known positive numbers are tested.The precondition n >= 0J is not tested, passing negative arguments may cause any kind of havoc.2Test whether a non-negative number may be a square. Non-negativity is not checked, passing negative arguments may cause any kind of havoc.First the remainder modulo 256 is checked (that can be calculated easily without division and eliminates about 82% of all numbers). After that, the remainders modulo 9, 25, 7, 11 and 13 are tested to eliminate altogether about 99.436% of all numbers.This is the test used by /@. For large numbers, the slower but more discriminating test isPossibleSqure2 is faster.3Test whether a non-negative number may be a square. Non-negativity is not checked, passing negative arguments may cause any kind of havoc.First the remainder modulo 256 is checked (that can be calculated easily without division and eliminates about 82% of all numbers). After that, the remainders modulo several small primes are tested to eliminate altogether about 99.98954% of all numbers.JFor smallish to medium sized numbers, this hardly performs better than 2, which uses smaller arrays, but for large numbers, where calculating the square root becomes more expensive, it is much faster (if the vast majority of tested numbers aren't squares).-./0123 !"#$%&-./0123-./0123-./0123 !"#$%& (c) 2012 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None34 totientSum n is, for n > 0 , the sum of otient k | k <- [1 .. n]]f, computed via generalised Moebius inversion. Arguments less than 1 cause an error to be raised.5generalInversion g n0 evaluates the generalised Moebius inversion of g at the argument n.yThe generalised Moebius inversion implemented here allows an efficient calculation of isolated values of the function  f : N -> Z if the function g defined by , g n = sum [f (n `quot` k) | k <- [1 .. n]] Kcan be cheaply computed. By the generalised Moebius inversion formula, then 8 f n = sum [moebius k * g (n `quot` k) | k <- [1 .. n]]  which allows the computation in O(n) steps, if the values of the Moebius function are known. A slightly different formula, used here, does not need the values of the Moebius function and allows the computation in O(n^0.75) steps, using O(n^0.5) memory.}An example of a pair of such functions where the inversion allows a more efficient computation than the direct approach is x f n = number of reduced proper fractions with denominator <= n g n = number of proper fractions with denominator <= n (a proper fraction is a fraction  0 < n/d < 1). Then f n6 is the cardinality of the Farey sequence of order nr (minus 1 or 2 if 0 and/or 1 are included in the Farey sequence), or the sum of the totients of the numbers  2 <= k <= n. f n0 is not easily directly computable, but then g n = n*(n-1)/2\ is very easy to compute, and hence the inversion gives an efficient method of computing f n.ISince the function arguments are used as array indices, the domain of f is restricted to . The value f n is then computed by generalInversion g n$). Note that when many values of ft are needed, there are far more efficient methods, this method is only appropriate to compute isolated values of f.45'455445' (c) 2012 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None36 totientSum n is, for n > 0 , the sum of otient k | k <- [1 .. n]]f, computed via generalised Moebius inversion. Arguments less than 1 cause an error to be raised.7generalInversion g n0 evaluates the generalised Moebius inversion of g at the argument n.yThe generalised Moebius inversion implemented here allows an efficient calculation of isolated values of the function  f : N -> Z if the function g defined by , g n = sum [f (n `quot` k) | k <- [1 .. n]] Kcan be cheaply computed. By the generalised Moebius inversion formula, then 8 f n = sum [moebius k * g (n `quot` k) | k <- [1 .. n]]  which allows the computation in O(n) steps, if the values of the Moebius function are known. A slightly different formula, used here, does not need the values of the Moebius function and allows the computation in O(n^0.75) steps, using O(n^0.5) memory.}An example of a pair of such functions where the inversion allows a more efficient computation than the direct approach is w f n = number of reduced proper fractions with denominator <= n g n = number of proper fractions with denominator <= n (a proper fraction is a fraction  0 < n/d < 1). Then f n6 is the cardinality of the Farey sequence of order nr (minus 1 or 2 if 0 and/or 1 are included in the Farey sequence), or the sum of the totients of the numbers  2 <= k <= n. f n0 is not easily directly computable, but then g n = n*(n-1)/2\ is very easy to compute, and hence the inversion gives an efficient method of computing f n.For  valued functions, unboxed arrays can be used for greater efficiency. That bears the risk of overflow, however, so be sure to use it only when it's safe. The value f n is then computed by generalInversion g n$). Note that when many values of ft are needed, there are far more efficient methods, this method is only appropriate to compute isolated values of f.67(677667((c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None38!Compact store of primality flags.9Sieve primes up to (and including) a bound. For small enough bounds, this is more efficient than using the segmented sieve.Since arrays are <-indexed, overflow occurs when the sieve size comes near  :: -, that corresponds to an upper bound near 15/8*. On 32Y-bit systems, that is often within memory limits, so don't give bounds larger than 8*10^9 there.:4Generate a list of primes for consumption from a 8.;List of primes. Since the sieve uses unboxed arrays, overflow occurs at some point. On 64-bit systems, that point is beyond the memory limits, on 32-bit systems, it is at about  1.7*10^18.<(List of primes in the form of a list of 8s, more compact than ;, thus it may be better to use < >>= :@ than keeping the list of primes alive during the entire run.)Sieve up to bound in one go.== n* creates the list of primes not less than n.>> n creates the list of 8s starting roughly at nW. Due to the organisation of the sieve, the list may contain a few primes less than n%. This form uses less memory than []B, hence it may be preferable to use this if it is to be reused.8*+,-./09:;<12)345=>6789:8*,-/09:;<)5=>6798*+,-./09:;<12)345=>6789: (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None89:;<=>;=89<>:(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None; Factorise an  using a given list of numbers considered prime. If the list is not a list of primes containing all relevant primes, the result could be surprising.?? bound n produces a factorisation of n using the primes <= bound. If n has prime divisors > bound@, the last entry in the list is the product of all these. If  n <= bound^24, this is a full factorisation, but very slow if n has large prime divisors.<Check whether a number is coprime to all of the numbers in the list (assuming that list contains only numbers > 1 and is ascending).@@ bound n tests whether n is coprime to all primes <= bound. If  n <= bound^2., this is a full prime test, but very slow if n has no small prime divisors.;?<@;?<@;?<@(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None;AA n tests whether nU is a prime (negative or positive). First, trial division by the primes less than 1200k is performed. If that hasn't determined primality or compositeness, a Baillie PSW test is performed.Since the Baillie PSW test may not be perfect, it is possible that some large composites are wrongly deemed prime, however, no composites passing the test are known and none exist below 2^64.BA Miller-Rabin like probabilistic primality test with preceding trial division. While the classic Miller-Rabin test uses randomly chosen bases, B k n uses the kn smallest primes as bases if trial division has not reached a conclusive result. (Only the primes up to 1200; are available in this module, so the maximal effective k is 196.)CC n b tests whether n/ is a strong Fermat probable prime for base b, where n > 2 and  1 < b < n5. The conditions on the arguments are not checked.'Apart from primes, also some composite numbers have the tested property, but those are rare. Very rare are composite numbers having the property for many bases, so testing a large prime candidate with several bases can identify composite numbers with high probability. An odd number n > 3 is prime if and only if C n b holds for all b with 2 <= b <= (n-1)/2 , but of course checking all those bases would be less efficient than trial division, so one normally checks only a relatively small number of bases, depending on the desired degree of certainty. The probability that a randomly chosen base doesn't identify a composite number n is less than 1/4J, so five to ten tests give a reasonable level of certainty in general.&Some notes about the choice of bases: b is a strong Fermat base for n if and only if n-b is, hence one needs only test  b <= (n-1)/2. If b is a strong Fermat base for n , then so is b^k = n for all k > 1h, hence one needs not test perfect powers, since their base yields a stronger condition. Finally, if a and b are strong Fermat bases for n, then a*b. is in most cases a strong Fermat base for n, it can only fail to be so if n = 4 == 1D and the strong Fermat condition is reached at the same step for a as for b3, so primes are the most powerful bases to test.DD n b tests whether n, is a Fermat probable prime for the base b, that is, whether b^(n-1) = n == 1. This is a weaker but simpler condition. However, more is lost in strength than is gained in simplicity, so for primality testing, the strong check should be used. The remarks about the choice of bases to test from C( apply with the modification that if a and b are Fermat bases for n, then a*b always is a Fermat base for n too. A Charmichael number is a composite number n3 which is a Fermat probable prime for all bases b coprime to n. By the above, only primes p <= n/2 not dividing nI need to be tested to identify Carmichael numbers (however, testing all those primes would be less efficient than determining Carmichaelness from the prime factorisation; but testing an appropriate number of prime bases is reasonable to find out whether it's worth the effort to undertake the prime factorisation).EPrimality test after Baillie, Pomerance, Selfridge and Wagstaff. The Baillie PSW test consists of a strong Fermat probable primality test followed by a (strong) Lucas primality test. This implementation assumes that the number n to test is odd and larger than 3. Even and small numbers have to be handled before. Also, before applying this test, trial division by small primes should be performed to identify many composites cheaply (although the Baillie PSW test is rather fast, about the same speed as a strong Fermat test for four or five bases usually, it is, for large numbers, much more costly than trial division by small primes, the primes less than 1000X, say, so eliminating numbers with small prime factors beforehand is more efficient).The Baillie PSW test is very reliable, so far no composite numbers passing it are known, and it is known (Gilchrist 2010) that no Baillie PSW pseudoprimes exist below 2^64. However, a heuristic argument by Pomerance indicates that there are likely infinitely many Baillie PSW pseudoprimes. On the other hand, according to  :http://mathworld.wolfram.com/Baillie-PSWPrimalityTest.html there is reason to believe that there are none with less than several thousand digits, so that for most use cases the test can be considered definitive.>pThe Lucas-Selfridge test, including square-check, but without the Fermat test. For package-internal use only.ABCDE>?@ABCDE>ABCDE>?@(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None3;F.Calculate the integer cube root of an integer n!, that is the largest integer r such that r^3 <= n+. Note that this is not symmetric about 0, for example integerCubeRoot (-2) = (-2) while integerCubeRoot 2 = 1.G9Calculate the integer cube root of a nonnegative integer n", that is, the largest integer r such that r^3 <= n. The precondition n >= 0 is not checked.HReturns Nothing# if the argument is not a cube, Just r if n == r^3.I"Test whether an integer is a cube.J8Test whether a nonnegative integer is a cube. Before F is calculated, a few tests of remainders modulo small primes weed out most non-cubes. For testing many numbers, most of which aren't cubes, this is much faster than  let r = cubeRoot n in r*r*r == n. The condition n >= 0 is not checked.K}Test whether a nonnegative number is possibly a cube. Only about 0.08% of all numbers pass this test. The precondition n >= 0 is not checked.AHapproximate cube root, about 50 bits should be correct for large numbersFGHIJKBCDEFAGHIJFGHIJKFGHIJKFGHIJKBCDEFAGHIJ(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None3;L[Calculate the integer fourth root of a nonnegative number, that is, the largest integer r with r^4 <= n'. Throws an error on negaitve input.M[Calculate the integer fourth root of a nonnegative number, that is, the largest integer r with r^4 <= n. The condition is not checked.NReturns Nothing if n is not a fourth power, Just r if n == r^4 and r >= 0.OsTest whether an integer is a fourth power. First nonnegativity is checked, then the unchecked test is called.PITest whether a nonnegative number is a fourth power. The condition is not$ checked. If a number passes the Q0 test, its integer fourth root is calculated.QRTest whether a nonnegative number is a possible fourth power. The condition is not6 checked. This eliminates about 99.958% of numbers.LMNOPQKLMNOPQRSLMNOPQLMNOPQLMNOPQKLMNOPQRS(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None; RCalculate the integer logarithm for an arbitrary base. The base must be greater than 1, the second argument, the number whose logarithm is sought, must be positive, otherwise an error is thrown. If  base == 2[, the specialised version is called, which is more efficient than the general algorithm. Satisfies: Fbase ^ integerLogBase base m <= m < base ^ (integerLogBase base m + 1)for base > 1 and m > 0.S&Calculate the integer logarithm of an K to base 2. The argument must be positive, otherwise an error is thrown.T&Calculate the integer logarithm of an K to base 2. The argument must be positive, otherwise an error is thrown.U%Calculate the integer logarithm of a K to base 2. The argument must be positive, otherwise an error is thrown.VSame as ST, but without checks, saves a little time when called often for known good input.WSame as TT, but without checks, saves a little time when called often for known good input.XSame as UT, but without checks, saves a little time when called often for known good input.Y&Calculate the integer logarithm of an L to base 10. The argument must be positive, otherwise an error is thrown.ZSame as Yp, but without a check for a positive argument. Saves a little time when called often for known good input.[Same as RT, but without checks, saves a little time when called often for known good input. RSTUVWXYZ[T RSTUVWXYZ[ RSYTU[VZWX RSTUVWXYZ[T(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None;\Calculate an integer root, \ k n computes the (floor of) the k-th root of n, where k must be positive. r = \ k n means r^k <= n < (r+1)^k4 if that is possible at all. It is impossible if k is even and n < 0 , since then r^k >= 0 for all r, then, and if k <= 0, \ raises an error. For k < 5, a specialised version is called which should be more efficient than the general algorithm. However, it is not guaranteed that the rewrite rules for those fire, so if kO is known in advance, it is safer to directly call the specialised versions.]] k n returns  if n is not a k-th power,  r if n == r^k. If k is divisible by 4, 3 or 2i, a residue test is performed to avoid the expensive calculation if it can thus be determined that n is not a k -th power.^^ k n checks whether n is a k -th power.__ n checks whether n == r^k for some k > 1.`` n produces the pair (b,k) with the largest exponent k such that n == b^k , except for U n <= 1V, in which case arbitrarily large exponents exist, and by an arbitrary decision (n,3) is returned.^First, by trial division with small primes, the range of possible exponents is reduced (if p^e exactly divides n, then k must be a divisor of e!, if several small primes divide n, kX must divide the greatest common divisor of their exponents, which mostly will be 1:, generally small; if none of the small primes divides n, the range of possible exponents is reduced since the base is necessarily large), if that has not yet determined the result, the remaining factor is examined by trying the divisors of the gcdg of the prime exponents if some have been found, otherwise by trying prime exponents recursively.aa bd n produces the pair (b,k) with the largest exponent k such that n == b^k, where bd > 1 (it is expected that bd is much larger, at least 1000 or so), n > bd^2 and n has no prime factors p <= bd*, skipping the trial division phase of `0 when that is a priori known to be superfluous. It is only present to avoid duplication of work in factorisation and primality testing, it is not expected to be generally useful. The assumptions are not checked, if they are not satisfied, wrong results and wasted work may be the consequence.\]^_`aVWXYZ[\]^_`ab\]^_`a\]^_`a\]^_`aVWXYZ[\]^_`ab(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None-/0FHILNO\]^_`-0/FIHLON\^]_`(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None; bb n% produces the prime factorisation of n, including a factor of (-1) if n < 0. b 0) is an error and the factorisation of 1 is empty. Uses a c< produced in an arbitrary manner from the bit-pattern of n.cLike b$, but without input checking, hence n > 1 is required.dd is like c, except that it doesn't use a pseudo random generator but steps through the curves in order. This strategy turns out to be surprisingly fast, on average it doesn't seem to be slower than the c based variant.ee first strips off all small prime factors and then, if the factorisation is not complete, proceeds to curve factorisation. For negative numbers, a factor of -1# is included, the factorisation of 1 is empty. Since 0@ has no prime factorisation, a zero argument causes an error.fLike e$, but without input checking, so n must be larger than 1.gA wrapper around h= providing a few default arguments. The primality test is E, the prng function - naturally - dR. This function also requires small prime factors to have been stripped before.hh is the driver for the factorisation. Its performance (and success) can be influenced by passing appropriate arguments. If you know that n has no prime divisors below b, any divisor found less than b*b must be prime, thus giving  Just (b*b)f as the first argument allows skipping the comparatively expensive primality test for those. If n is such that all prime divisors must have a specific easy to test for structure, a custom primality test can improve the performance (normally, it will make very little difference, since n has not many divisors, and many curves have to be tried to find one). More influence has the pseudo random generator (a function prng with 6 <= fst (prng k s) <= k-2 and an initial state for the PRNG) used to generate the curves to try. A lucky choice here can make a huge difference. So, if the default takes too long, try another one; or you can improve your chances for a quick result by running several instances in parallel.hd requires that small prime factors have been stripped before. Also, it is unlikely to succeed if n/ has more than one (really) large prime factor.ii n b1 b2 s tries to find a factor of n5 using the curve and point determined by the seed s ( 6 <= s < n-1H), multiplying the point by the least common multiple of all numbers <= b1 and all primes between b1 and b2. The idea is that there's a good chance that the order of the point in the curve over one prime factor divides the multiplier, but the order over another factor doesn't, if b1 and b2 are appropriately chosen. If they are too small, none of the orders will probably divide the multiplier, if they are too large, all probably will, so they should be chosen to fit the expected size of the smallest factor.It is assumed that n has no small prime factors.,The result is maybe a nontrivial divisor of n.jj bound n finds all prime divisors of n > 1 up to bound by trial division and returns the list of these together with their multiplicities, and a possible remaining factor which may be composite.efghbcdefg"Lower bound for composite divisors Standard PRNG3Estimated number of digits of smallest prime factorThe number to factorise#List of prime factors and exponentsh"Lower bound for composite divisorsA primality testA PRNGInitial PRNG state7Estimated number of digits of the smallest prime factorThe number to factorise#List of prime factors and exponentsiijklmnjopqr bcdefghijrefghbcdefghiijklmnjopqr(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None3M k5A compact store of values of the Carmichael function.lA compact store of totients.m*A compact store of smallest prime factors.nn nH creates a store of smallest prime factors of the numbers not exceeding n. If you need to factorise many smallish numbers, this can give a big speedup since it avoids many superfluous divisions. However, a too large sieve leads to a slowdown due to cache misses. The prime factors are stored as s for compactness, so n must be smaller than 2^32.tt sieveF tells the limit to which the sieve stores the smallest prime factors.uu sieve n checks in the sieve whether n is prime. If n< is larger than the sieve can handle, an error is raised.oo fs n" finds the prime factorisation of n using the m fs. For negative n, a factor of -1 is included with multiplicity 1). After stripping any present factors 2, the remaining cofactor c (if larger than 1) is factorised with fs&. This is most efficient of course if c) does not exceed the bound with which fs was constructed. If it does, trial division is performed until either the cofactor falls below the bound or the sieve is exhausted. In the latter case, the elliptic curve method is used to finish the factorisation.pp n> creates a store of the totients of the numbers not exceeding n. A l+ only stores values for numbers coprime to 30< to reduce space usage. The maximal admissible value for n is  ( :: ).qq ts n finds the totient (n), i.e. the number of integers k with  1 <= k <= n and  n k == 18, in other words, the order of the group of units in !$/(n) , using the l ts. First, factors of 2, 3 and 5; are handled individually, if the remaining cofactor of n is within the sieve range, its totient is looked up, otherwise the calculation falls back on factorisation, first by trial division and if necessary, elliptic curves.rr nS creates a store of values of the Carmichael function for numbers not exceeding n . Like a l, a k+ only stores values for numbers coprime to 30< to reduce space usage. The maximal admissible value for n is  ( :: ).ss cs n finds the value of (n) (or (n)$), the smallest positive integer e such that for all a with  gcd a n == 1 the congruence a^e "a 1 (mod n)L holds, in other words, the (smallest) exponent of the group of units in !$/(n)". The strategy is analogous to q.kvlwmxntuopqrsyz{| klmntuopqrskvlwmxntuopqrsyz{|(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None t,Calculates the totient of a positive number n, i.e. the number of k with  1 <= k <= n and  n k == 18, in other words, the order of the group of units in !$/(n).u Alias of t% for people who prefer Greek letters.vxCalculates the Carmichael function for a positive integer, that is, the (smallest) exponent of the group of units in  &8484;/(n).w Alias of v% for people who prefer Greek letters.xx n* is the set of all (positive) divisors of n. x 04 is an error because we can't create the set of all s.yy n) is the number of (positive) divisors of n. y 0 is an error because 0 has infinitely many divisors.z Alias for y.{8The sum of all (positive) divisors of a positive number n-, calculated from its prime factorisation.| Alias for }.}} k n is the sum of the k,-th powers of the (positive) divisors of n. k must be non-negative and n positive. For k == 0, it is the divisor count (d^0 = 1).~ Alias for }% for people preferring Greek letters. Alias for y% for people preferring Greek letters. tuvwxyz{|}~%'()*+,?bcdefghijklmnopqrstuvwxyz{|}~%bedcfmno?jghitulpq'vwkrs(xyz{}~|)*+, tuvwxyz{|}~(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None%5An argument for primality of a number (which must be > 1). s translate directly to PrimalityArguments, correct arguments can be transformed into proofs. This type allows the manipulation of proofs while maintaining their correctness. The only way to access components of a * except the prime is through this type.Primality assumedaprime6 is said to be obviously prime, that holds for primes < 302Primality should be provable by trial division to alimit#A suggested Pocklington certificatedA proof of primality of a positive number. The type is abstract to ensure the validity of proofs.%The number whose primality is proved.9An argument for compositeness of a number (which must be > 1). s translate directly to CompositenessArguments, correct arguments can be transformed into proofs. This type allows the manipulation of proofs while maintaining their correctness. The only way to access components of a . except the composite is through this type.No particular reason givencompo fails the Lucas-Selfridge testcompo" fails the strong Fermat test for  fermatBasecompo == firstDiv*secondDiv, where all are > 1hA proof of compositeness of a positive number. The type is abstract to ensure the validity of proofs.)The number whose compositeness is proved.<A certificate of either compositeness or primality of an . Only numbers > 1W can be certified, trying to create a certificate for other numbers raises an error.@ transforms a proof of primality into an argument for primality. checks the given argument and constructs a proof from it, if it is valid. For the explicit arguments, this is simple and resonably fast, for an , the verification uses  and hence may take a long time.}Knot exported, this is the one place where invalid proofs can be constructedK transforms a proof of compositeness into an argument for compositeness. checks the given argument and constructs a proof from it, if it is valid. For the explicit arguments, this is simple and resonably fast, for a , the verification uses  and hence may take a long time.~Tnot exported, here is where invalid proofs can be constructed, they must not leakCheck the validity of a z. Since it should be impossible to construct invalid certificates by the public interface, this should never return .Check the validity of a q. Since it should be impossible to create invalid proofs by the public interface, this should never return .Check the validity of a q. Since it should be impossible to create invalid proofs by the public interface, this should never return .\ records a trivially known prime. If the argument is not one of them, an error is raised.\ finds out if its argument is a trivially known prime or not and returns the appropriate.; checks whether its argument is a trivially known prime.List of trivially known primes.Certify a small number. This is not exposed and should only be used where correct. It is always checked after use, though, so it shouldn't be able to lie. n constructs, for n > 15, a proof of either primality or compositeness of nR. This may take a very long time if the number has no small(ish) prime divisorsCertify a number known to be not too small, having no small prime divisors and having passed the Baillie PSW test. So we assume it's prime, erroring if not. Since it's presumably a large number, we don't bother with trial division and construct a Pocklington certificate.mFind a decomposition of p-1 for the pocklington certificate. Usually bloody slow if p-1 has two (or more) large prime divisors.Find a factor of a known composite with approximately digits digits, starting with curve s. Actually, this may loop infinitely, but the loop should not be entered before the heat death of the universe.2Find a factor or say with which curve to continue.@Message in the unlikely case a Baillie PSW pseudoprime is found.Found a factorFermat failure>}~3  }~(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None  n( produces the prime factorisation of nF, proving the primality of the factors, but doesn't report the proofs. n produces a  with a default bound of 100000. bound n) constructs a the prime factorisation of nm (which must be positive) together with proofs of primality of the factors, using trial division up to bound# (which is arbitrarily replaced by 2000q if the supplied value is smaller) and elliptic curve factorisation for the remaining factors if necessary.,Construction of primality proofs can take a veryM long time, so this will usually be slow (but should be faster than using b; and proving the primality of the factors from scratch).4verify that we indeed have a correct primality proofproduce a proof of primality for primes Only called for (not too small) numbers known to have no small prime factors, so we can directly use BPSW without trial division.produce a certified factorisation Assumes all small prime factors have been stripped before. Since it is not exported, that is known to hold. This is a near duplicate of h&, I should some time clean this up.Vmerge two lists of factors, so that the result is strictly increasing (wrt the primes)[merge a list of lists of factors so that the result is strictly increasing (wrt the primes)2message for an invalid proof, should never be used "Lower bound for composite divisorsA primality testA PRNGInitial PRNG state7Estimated number of digits of the smallest prime factorThe number to factorise5List of prime factors, exponents and primality proofs (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None#/ (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None n tests primality of n, first trial division by small primes is performed, then a Baillie PSW test and finally a prime certificate is constructed and verified, provided no step before found n@ to be composite. Constructing prime certificates can take a very" long time, so use this with care. (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneTest primality using a m. If n0 is out of bounds of the sieve, fall back to A. @ABCDEm AEBCDm@!(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> Provisional non-portableNone3 n == (n)2 is the number of (positive) primes not exceeding n.OFor efficiency, the calculations are done on 64-bit signed integers, therefore n must not exceed  8 * 10^18. Requires O(n^0.5)' space, the time complexity is roughly O(n^0.7). For small bounds,  n( simply counts the primes not exceeding n, for bounds from 30000T on, Meissel's algorithm is used in the improved form due to D.H. Lehmer, cf.  \http://en.wikipedia.org/wiki/Prime_counting_function#Algorithms_for_evaluating_.CF.80.28x.29. n calculates the n%-th prime. Numbering of primes is 1 -based, so  1 == 2. Requires O((n*log n)^0.5)' space, the time complexity is roughly O((n*log n)^0.7A. The argument must be strictly positive, and must not exceed  1.5 * 10^17.(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> Provisional non-portableNone"(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None8'()*+,89:;<=>?@ABCDEbcdefghijklmnopqrstuvwxyz{|}~#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO P Q R S T U V W X W XYZ[*\+]^_`abcdefghijklmnopqrstuvwxyz{|}~ !!Z       !"#$%&'()*+,-./01234567898:;<=>?@A@B C D E F G H I J K L M N O P Q QRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~!!!!!!!!!!!!!!arithmoi-0.4.1.3!Math.NumberTheory.Primes.CountingMath.NumberTheory.LucasMath.NumberTheory.Primes.HeapMath.NumberTheory.GCD.LowLevelMath.NumberTheory.GCDMath.NumberTheory.Moduli Math.NumberTheory.Powers.Integer&Math.NumberTheory.Primes.Factorisation Math.NumberTheory.Powers.Squares"Math.NumberTheory.MoebiusInversion&Math.NumberTheory.MoebiusInversion.IntMath.NumberTheory.Primes.Sieve Math.NumberTheory.Primes.TestingMath.NumberTheory.Powers.CubesMath.NumberTheory.Powers.FourthMath.NumberTheory.Logarithms Math.NumberTheory.Powers.General-Math.NumberTheory.Primes.Testing.Certificates0Math.NumberTheory.Primes.Factorisation.Certified'Math.NumberTheory.Primes.Sieve.Indexing-Math.NumberTheory.Primes.Counting.ApproximateMath.NumberTheory.Utils%Math.NumberTheory.Logarithms.Internal,Math.NumberTheory.Primes.Factorisation.Utils+Math.NumberTheory.Primes.Sieve.Eratosthenes4Math.NumberTheory.Primes.Factorisation.TrialDivision.Math.NumberTheory.Primes.Testing.ProbabilisticMath.NumberTheory.Powers1Math.NumberTheory.Primes.Factorisation.Montgomery#Math.NumberTheory.Primes.Sieve.Misc6Math.NumberTheory.Primes.Testing.Certificates.Internal*Math.NumberTheory.Primes.Testing.Certified&Math.NumberTheory.Primes.Counting.ImplMath.NumberTheory.PrimesapproxPrimeCountnthPrimeApprox fibonacci fibonacciPairlucas lucasPair generalLucasprimes sieveFromgcdInt coprimeIntgcdWord coprimeWordgcdInt# coprimeInt#gcdWord# coprimeWord# binaryGCD extendedGCDcoprime invertModjacobijacobi'powerMod powerMod'powerModIntegerpowerModInteger'sqrtModP sqrtModPList sqrtModP' tonelliShanks sqrtModPPsqrtModF sqrtModFList sqrtModPPListchineseRemainderchineseRemainder2 integerPowerintegerWordPowertotientFromCanonicalcarmichaelFromCanonicaldivisorsFromCanonicaltauFromCanonicaldivisorSumFromCanonicalsigmaFromCanonicalintegerSquareRootintegerSquareRoot'exactSquareRootisSquare isSquare'isPossibleSquareisPossibleSquare2 totientSumgeneralInversion PrimeSieve primeSieve primeList psieveList psieveFromtrialDivisionTotrialDivisionPrimeToisPrime millerRabinVisStrongFermatPP isFermatPP bailliePSWintegerCubeRootintegerCubeRoot' exactCubeRootisCubeisCube'isPossibleCubeintegerFourthRootintegerFourthRoot'exactFourthRoot isFourthPowerisFourthPower'isPossibleFourthPowerintegerLogBase integerLog2intLog2wordLog2 integerLog2'intLog2' wordLog2' integerLog10 integerLog10'integerLogBase' integerRoot exactRoot isKthPowerisPerfectPower highestPower largePFPower factorise factorise'stepFactorisationdefaultStdGenFactorisationdefaultStdGenFactorisation'stdGenFactorisationcurveFactorisationmontgomeryFactorisation smallFactorsCarmichaelSieve TotientSieve FactorSieve factorSieve sieveFactor totientSieve sieveTotientcarmichaelSievesieveCarmichaeltotientφ carmichaelλdivisorstau divisorCount divisorSumdivisorPowerSumsigmaστPrimalityArgument AssumptionObviousDivisionalimitPockaprime largeFactor smallFactor factorListPrimalityProofcprimeCompositenessArgumentBeliefLucasFermat fermatBaseDivisorscompo firstDivisor secondDivisorCompositenessProof composite CertificatePrime CompositeargueCertificatearguePrimalityverifyPrimalityArgumentargueCompositenessverifyCompositenessArgumentcheckCertificatecheckCompositenessProofcheckPrimalityProofcertifycertifiedFactorisationcertificateFactorisationprovenFactorisationisCertifiedPrime fsIsPrime primeCountnthPrimeidxPrtoPrimtoIdxrhoresiduesdeltadeltastausbyte startByteidxstartIdxmunumArrnArrappinthAppbaseGHC.EnummaxBoundGHC.BasemapGHC.Num fromIntegerGHC.List takeWhileGHC.Real fromIntegralghc-prim GHC.TypesIntWord integer-gmpGHC.Integer.TypeIntegerHippHEDelDsteppushbubblemkHippincadjustbuildH simpleSieve feederSievefeedersieve nextIndex wheelPrimesfindIx remaindersstepsshiftToOddCount shiftOCWord shiftOCIntshiftOCInteger shiftToOdd shiftOInt shiftOWord shiftOInteger shiftToOdd#shiftToOddCount# bitCountWord#GHC.PrimWord# bitCountWord bitCountInt trailZeros#uncheckedShiftRsplitOffInt# gcdWordOdd#oddGCD#absInt#gcdminBoundgi64gw64 binaryGCDImplci64cw64 coprimeImplgcdOddoddGCDgi8gi16gi32gw8gw16gw32ci8ci16ci32cw8cw16cw32jacPSjacOL powerModImpl powerMod'ImplsqM2PevenIrem4rem8jac2 findNonSquareGHC.Integer.Logarithms wordLog2# integerLog2#hasBit#power ppTotientppDivSum ppDivPowerSum Data.MaybeNothingJustisqrtAheronappSqrt sqRemArraysr256sr819sr4097sr341sr1025sr2047sr693sr325 isqrtInt' isqrtWord fastInvertsieveToPS CacheWord sieveBytes sieveBits lastIndex sieveRange sieveWords makeSievesslice growCache countFromToWd countFromTo nthPrimeCt countToNth countDowncountAlltoptrialDivisionWithtrialDivisionPrimeWithmod lucasTest testLucas smallPrimesappCuRt cubeRootInt' cubeRootWord cubeRootIgrnewton3 approxCuRtcr512 cubeRes837 cubeRes637 cubeRes703newton4 approxBiSqrt appBiSqrt biSqRes256 biSqRes425 biSqRes377 biSqrtInt biSqrtWord biSqrtIgrlogArrabsnewtonK approxKthRoot appKthRootintegerHighPower findHighPowerspBExspBoundsmallOddPrimes finishPowerrawPower rawOddPowerbadPower divisorsTo random-1.1 System.RandomStdGenrandomRPointPCurveCmontgomeryDataadddoublemultiply primeStorelistmergemergeAll testParms findParmsGHC.WordWord16fsBound fsPrimeTestCSTSFSspfSievetotSievecarSieveunFact primProof compProofFalsetrivial maybeTrivialisTrivialPrime trivialPrimes smallCert certifyBPSWfindDecomposition findFactorfindLoop bpswMessagefoundfermatTrivial TrialDivisiontdLimit PocklingtonfactorisedPartcofactor knownFactorsLucasSelfridge StrongFermatwitnessFactors firstFactor secondFactortest primeCheckcertiFactorisationinvalidtooLowtooHighlowSieve sieveCountcalctreatlocatecopyTocopyRemcp6copcpCtArcpDfArcpGpAr