l      !"#$%&'()* + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~((c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneBRemove 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).Count trailing zeros in a E. Precondition: argument nonzero (not checked, Integer invariant).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) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNone (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)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.0123456789:;<=>?@ABCDE0123456789:;<=>?@ABCDE(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalportableSafeFollowing property holds: LapproxPrimeCount n >= primeCount n || n >= approxPrimeCountOverestimateLimit nD gives an approximation of the number of primes not exceeding n'. The approximation is fairly good for n large enough.Following property holds: GnthPrimeApprox n <= nthPrime n || n >= nthPrimeApproxUnderestimateLimit nV gives an approximation to the n-th prime. The approximation is fairly good for n large enough.FGFG(c) 2011-2014 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneB 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 .HA raw version of testBit for  .IHIH(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneJTotient 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. @Calculate the Moebius function from the canonical factorisation. 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. J KLJ  J KL(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None:B[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.[Calculate the integer fourth root of a nonnegative number, that is, the largest integer r with r^4 <= n. The condition is not checked.Returns Nothing if n is not a fourth power, Just r if n == r^4 and r >= 0.sTest whether an integer is a fourth power. First nonnegativity is checked, then the unchecked test is called.ITest whether a nonnegative number is a fourth power. The condition is not$ checked. If a number passes the 0 test, its integer fourth root is calculated.RTest whether a nonnegative number is a possible fourth power. The condition is not6 checked. This eliminates about 99.958% of numbers.MNOPQRSTUMNOPQRSTU(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None:B.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.9Calculate 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.Returns Nothing# if the argument is not a cube, Just r if n == r^3."Test whether an integer is a cube.8Test whether a nonnegative integer is a cube. Before  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.}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.VHapproximate cube root, about 50 bits should be correct for large numbersWXYZ[V\]^_WXYZ[V\]^_(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)Safe 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)NoneB Calculate 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.!&Calculate the integer logarithm of an K to base 2. The argument must be positive, otherwise an error is thrown."&Calculate the integer logarithm of an K to base 2. The argument must be positive, otherwise an error is thrown.#%Calculate the integer logarithm of a K to base 2. The argument must be positive, otherwise an error is thrown.$Same as !T, but without checks, saves a little time when called often for known good input.%Same as "T, but without checks, saves a little time when called often for known good input.&Same as #T, but without checks, saves a little time when called often for known good input.'&Calculate the integer logarithm of an L to base 10. The argument must be positive, otherwise an error is thrown.(Same as 'p, but without a check for a positive argument. Saves a little time when called often for known good input.)Same as  T, but without checks, saves a little time when called often for known good input. !"#$%&'()` !"#$%&'() !'"#)$(%& !"#$%&'()` (c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None:B*ab+cde*++**ab+cde (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None:B ,: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..Calculate the integer square root of a nonnegative number as well as the difference of that number with the square of that root, that is if (s,r) = integerSquareRootRem n then s^2 <= n == s^2+r < (s+1)^2./Calculate the integer square root of a nonnegative number as well as the difference of that number with the square of that root, that is if (s,r) = integerSquareRootRem' n then s^2 <= n == s^2+r < (s+1)^2. The precondition n >= 0 is not checked.0Returns f% if the argument is not a square, g 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 3.1XTest whether the argument is a square. After a number is found to be positive, first 3@ is checked, if it is, the integer square root is calculated.2.Test whether the input (a nonnegative number) n is a square. The same as 1W, 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.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 9, 25, 7, 11 and 13 are tested to eliminate altogether about 99.436% of all numbers.This is the test used by 0@. For large numbers, the slower but more discriminating test isPossibleSqure2 is faster.4Test 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 3, 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).,-./01234hijklmnopqrs ,-./01234 ,-./01234,-./01234hijklmnopqrs (c) 2012 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None:5 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.6generalInversion 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.56t566556t (c) 2012 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None:7 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.8generalInversion 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.78u788778u (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneB9Calculate an integer root, 9 k n computes the (floor of) the k-th root of n, where k must be positive. r = 9 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, 9 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 f if n is not a k-th power, g 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 v 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.>> 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.9:;<=>wxyz{|}~9:;<=>9:;<=>9:;<=>wxyz{|}~(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None:?!Compact store of primality flags.@Sieve primes up to (and including) a bound (or 7, if bound is smaller). 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.A4Generate a list of primes for consumption from a ?.BList 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.C(List of primes in the form of a list of ?s, more compact than B, thus it may be better to use C >>= A@ than keeping the list of primes alive during the entire run.Sieve up to bound in one go.DD n* creates the list of primes not less than n.EE n creates the list of ?s 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.?@ABCDE?@ABCDE?@ABCDE(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.FF 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).GG 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.FGFGFG(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None?@ABCDEBD?@CEA(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> Provisional non-portableNone:HMaximal allowed argument of I. Currently 8e18.II 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 H. Requires O(n^0.5)' space, the time complexity is roughly O(n^0.7). For small bounds, I 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.JMaximal allowed argument of K. Currently 1.5e17.KK n calculates the n%-th prime. Numbering of primes is 1 -based, so K 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 J.HIJKHIJKHIJK(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> Provisional non-portableNoneHIJKIHKJ(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneBLGreatest common divisor of two ,s, calculated with the binary gcd algorithm.MTest whether two 9s are coprime, using an abbreviated binary gcd algorithm.NGreatest common divisor of two ,s, calculated with the binary gcd algorithm.OTest whether two 9s are coprime, using an abbreviated binary gcd algorithm.PGreatest common divisor of two ,s, calculated with the binary gcd algorithm.QTest whether two s are coprime.RGreatest common divisor of two  ,s, calculated with the binary gcd algorithm.STest whether two  s are coprime. LMNOPQRSLMNOPQRSLNPRMOQS LMNOPQRS(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneBTCalculate 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.UdCalculate the greatest common divisor of two numbers and coefficients for the linear combination.For signed types satisfies: Tcase extendedGCD a b of (d, u, v) -> u*a + v*b == d && d == gcd a bCFor unsigned and bounded types the property above holds, but since u and vS must also be unsigned, the result may look weird. E. g., on 64-bit architecture 5extendedGCD (2 :: Word) (3 :: Word) == (1, 2^64-1, 1)'For unsigned and unbounded types (like  !) the result is undefined.For signed types we also have 8abs 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).VuTest 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 TK 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.TUVTUVTUVTUV(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneW6Invert a number relative to a positive modulus. If number and modulus are coprime, the result is  Just inverse where B (number * inverse) `mod` modulus == 1 0 <= inverse < modulusIf number  modulus == 0 or gcd number modulus > 1, the result is Nothing.XgJacobi 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.YLJacobi symbol of two numbers without validity check of the "denominator".ZModular power. powerMod base exponent modulus calculates (base ^ exponent) `mod` modulusE by repeated squaring and reduction. Modulus must be positive. 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 Z for T exponents. Reduces the number of shifts of the exponent since shifting large zs is expensive. Call this function directly if you don't want or can't rely on rewrite rules. Modulus must be positive.]^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 square must+ be a positive quadratic residue modulo prime, i.e. 'jacobi square prime == 1. The precondition is not checked.atonelliShanks 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 positive quadratic residue modulo primeQ, using the Tonelli-Shanks algorithm. No checks on the input are performed.bsqrtModPP 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 primecsqrtModF n primePowers calculates a square root of n modulo $product [p^k | (p,k) <- primePowers]N if one exists and all primes are distinct. The list must be non-empty, n! must be coprime with all primes.dsqrtModFList n primePowers calculates all square roots of n modulo $product [p^k | (p,k) <- primePowers]< if all primes are distinct. The list must be non-empty, n! must be coprime with all primes.esqrtModPPList n (prime,expo)/ calculates the list of all square roots of n modulo  prime^expo . The same restriction as in b applies to the arguments.f 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) Lif all moduli are positive and pairwise coprime. Otherwise the result is Nothing, regardless of whether a solution exists.g%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.WXYZ[\]^_`abcdefgWXYZ[\]^_`abcdefgXWZ\f^Y[]_`abecdgWXYZ[\]^_`abcdefg"(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None,019:;<=Z,109;:<=Z#(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneBhh 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.iA Miller-Rabin like probabilistic primality test with preceding trial division. While the classic Miller-Rabin test uses randomly chosen bases, i 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.)jj 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 j 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.kk 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 j( 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).lPrimality 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.hijklhijklhijkl$(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneB mm n% produces the prime factorisation of n, including a factor of (-1) if n < 0. m 0) is an error and the factorisation of 1 is empty. Uses a < produced in an arbitrary manner from the bit-pattern of n.nLike m$, but without input checking, hence n > 1 is required.oo is like n, 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  based variant.pp 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.qLike p$, but without input checking, so n must be larger than 1.rA wrapper around s= providing a few default arguments. The primality test is l, the prng function - naturally - R. This function also requires small prime factors to have been stripped before.ss 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.sd 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.tt 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.uu 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.mnopqr"Lower bound for composite divisors Standard PRNG3Estimated number of digits of smallest prime factorThe number to factorise#List of prime factors and exponentss"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 exponentstu mnopqrstumnopqrstu%(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None:T v5A compact store of values of the Carmichael function.wA compact store of totients.x*A compact store of smallest prime factors.yy 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  for compactness, so n must be smaller than 2^32. sieveF tells the limit to which the sieve stores the smallest prime factors. sieve n checks in the sieve whether n is prime. If n< is larger than the sieve can handle, an error is raised.zz fs n" finds the prime factorisation of n using the x 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.{{ n> creates a store of the totients of the numbers not exceeding n. A w+ only stores values for numbers coprime to 30< to reduce space usage. The maximal admissible value for n is / (+ :: ).|| 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 w 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.}} nS creates a store of values of the Carmichael function for numbers not exceeding n . Like a w, a v+ only stores values for numbers coprime to 30< to reduce space usage. The maximal admissible value for n is / (+ :: ).~~ 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 |.vwxyz{|}~ vwxyz{|}~vwxyz{|}~(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None,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). Alias of % for people who prefer Greek letters.xCalculates the Carmichael function for a positive integer, that is, the (smallest) exponent of the group of units in !$/(n). Alias of % for people who prefer Greek letters.7Calculates the Moebius function for a positive integer. Alias of % for people who prefer Greek letters. n* is the set of all (positive) divisors of n.  04 is an error because we can't create the set of all s. n) is the number of (positive) divisors of n.  0 is an error because 0 has infinitely many divisors. Alias for .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 % for people preferring Greek letters.( Fmnopqrstuvwxyz{|}~(mponqxyzFurstw{|v}~ &(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.#A suggested Pocklington certificate2Primality should be provable by trial division to alimitaprime6 is said to be obviously prime, that holds for primes < 30Primality assumeddA 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.compo == firstDiv*secondDiv, where all are > 1compo" fails the strong Fermat test for  fermatBasecompo fails the Lucas-Selfridge testNo particular reason givenhA 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 m; 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 s&, 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 x. If n0 is out of bounds of the sieve, fall back to h. Ghijklx hlijkxG(c) 2016 Chris FredricksonMIT1Chris Fredrickson <chris.p.fredrickson@gmail.com> ProvisionalNon-portable (GHC extensions)None<A Gaussian integer is a+bi, where a and b are both integers.The imaginary unit, where   .^ 2 == -1 Simultaneous   and  .2Gaussian integer division, truncating toward zero.&Gaussian integer remainder, satisfying #(x `quotG` y)*y + (x `remG` y) == x Simultaneous   and .?Gaussian integer division, truncating toward negative infinity.&Gaussian integer remainder, satisfying "(x `divG` y)*y + (x `modG` y) == xConjugate a Gaussian integer.2The square of the magnitude of a Gaussian integer.2Compute whether a given Gaussian integer is prime.An infinite list of the Gaussian primes. Uses primes in Z to exhaustively generate all Gaussian primes, but not quite in order of ascending magnitude.Compute the GCD of two Gaussian integers. Enforces the precondition that each integer must be in the first quadrant (or zero).GCompute the GCD of two Gauss integers. Does not check the precondition.rFind a Gaussian integer whose norm is the given prime number. Checks the precondition that p is prime and that p  4 /= 3._Find a Gaussian integer whose norm is the given prime number. Does not check the precondition.*Raise a Gaussian integer to a given power.TCompute the prime factorisation of a Gaussian integer. This is unique up to units (+- 1, +- i).  68(c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)NoneDR&The following invariant must hold for n /= 0: Eabs n == abs (product (map (\(p, k) -> unPrime p ^ k) (factorise n)))The result of l should not contain zero powers and should not change after multiplication of the argument by domain's unit.^Type of primes of a given unique factorisation domain. When the domain has exactly one unit,  Prime t = ta, but when units are multiple more restricted types (or at least newtypes) should be specified.abs (unPrime n) == unPrime n must hold for all n of type Prime t((c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None? ?@ABCDEFGHIJKhijklmnopqrstuvwxyz{|}~)(c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None%&A typical arithmetic function operates on the canonical factorisation of a number into prime's powers and consists of two rules. The first one determines the values of the function on the powers of primes. The second one determines how to combine these values into final result.In the following definition the first argument is the function on prime's powers, the monoid instance determines a rule of combination (typically   or !E), and the second argument is convenient for unwrapping (typically, " or #).1Convert to function. The value on 0 is undefined.$Factorisation is expensive, so it is better to avoid doing it twice. Write 'runFunction (f + g) n' instead of 'runFunction f n + runFunction g n'. %&$'()* %&$'()**(c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None$DRTYCreate a multiplicative function from the function on prime's powers. See examples below.2The set of all (positive) divisors of an argument.Same as :, but with better performance on cost of type restriction.1The number of (positive) divisors of an argument. %tauA = multiplicative (\_ k -> k + 1)The sum of the k1-th powers of (positive) divisors of an argument. HsigmaA = multiplicative (\p k -> sum $ map (p ^) [0..k]) sigmaA 0 = tauA,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).3Calculates the k-th Jordan function of an argument. jordanA 1 = totientA/Calculates the Moebius function of an argument.1Calculates the Liouville function of an argument.xCalculates the Carmichael function for a positive integer, that is, the (smallest) exponent of the group of units in !$/(n).TCreate an additive function from the function on prime's powers. See examples below.!Number of distinct prime factors. "smallOmegaA = additive (\_ _ -> 1)3Number of prime factors, counted with multiplicity.  bigOmegaA = additive (\_ k -> k)+The exponent of von Mangoldt function. Use log expMangoldtA) to recover von Mangoldt function itself.B+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQR4+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQR(c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)NoneS+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRST U V W X Y Z [ \ ] ^ _ ` a ` a b c d e f ghij+k,lmnopqrstuvwxyz{|}~#####$$$$$$$$$%%%%%%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'+)))************ * ** * * ********* !"#$%&'()*+,-./012312412512612712812912:12;<=>?@ABCDEFGHIJKLMNLOPLQRLSTLUVWXYZ[\]^_`abcdeifghijklmnopqrstuvwxyz{|}~     LOLO              LQ             *LULMLU###$$$$$$$$$$$$$$L%%%% % % % % %&&&&&&&&&&&&&&&&& &!&"&#&$&%&&&'&(&)&*+,-.LU/LU0LU123455677899:;<=>?@ALBCLBDLBELBF)G)H)I)J)K)L)M*N*N*O*P*P*Q*R*R*S*T*T*U*V*W*X*Y*Z*[*\*]*;*^*_*`*a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*pq'arithmoi-0.4.3.0-6KZ3b1XroeK8nkq91xUUMPMath.NumberTheory.Primes.Heap!Math.NumberTheory.Primes.Counting Math.NumberTheory.Powers.Integer&Math.NumberTheory.Primes.FactorisationMath.NumberTheory.Powers.FourthMath.NumberTheory.Powers.CubesMath.NumberTheory.LucasMath.NumberTheory.Logarithms)Math.NumberTheory.Powers.Squares.Internal Math.NumberTheory.Powers.Squares"Math.NumberTheory.MoebiusInversion&Math.NumberTheory.MoebiusInversion.Int Math.NumberTheory.Powers.GeneralMath.NumberTheory.Primes.Sieve Math.NumberTheory.Primes.TestingMath.NumberTheory.GCD.LowLevelMath.NumberTheory.GCDMath.NumberTheory.Moduli-Math.NumberTheory.Primes.Testing.Certificates0Math.NumberTheory.Primes.Factorisation.Certified"Math.NumberTheory.GaussianIntegers%Math.NumberTheory.UniqueFactorisation%Math.NumberTheory.ArithmeticFunctionsMath.NumberTheory.UtilsMath.NumberTheory.Unsafe'Math.NumberTheory.Primes.Sieve.Indexing-Math.NumberTheory.Primes.Counting.Approximate,Math.NumberTheory.Primes.Factorisation.Utils+Math.NumberTheory.Primes.Sieve.Eratosthenes4Math.NumberTheory.Primes.Factorisation.TrialDivision&Math.NumberTheory.Primes.Counting.ImplNumeric.NaturalNaturalMath.NumberTheory.Powers.Math.NumberTheory.Primes.Testing.Probabilistic1Math.NumberTheory.Primes.Factorisation.Montgomery#Math.NumberTheory.Primes.Sieve.Misc6Math.NumberTheory.Primes.Testing.Certificates.Internal*Math.NumberTheory.Primes.Testing.CertifiedMath.NumberTheory.Primes+Math.NumberTheory.ArithmeticFunctions.Class.Math.NumberTheory.ArithmeticFunctions.Standardprimes sieveFrom!approxPrimeCountOverestimateLimitapproxPrimeCount nthPrimeApproxUnderestimateLimitnthPrimeApprox integerPowerintegerWordPowertotientFromCanonicalcarmichaelFromCanonicalmoebiusFromCanonicaldivisorsFromCanonicaltauFromCanonicaldivisorSumFromCanonicalsigmaFromCanonicalintegerFourthRootintegerFourthRoot'exactFourthRoot isFourthPowerisFourthPower'isPossibleFourthPowerintegerCubeRootintegerCubeRoot' exactCubeRootisCubeisCube'isPossibleCube fibonacci fibonacciPairlucas lucasPair generalLucasintegerLogBase integerLog2intLog2wordLog2 integerLog2'intLog2' wordLog2' integerLog10 integerLog10'integerLogBase'isqrtA karatsubaSqrtintegerSquareRootintegerSquareRoot'integerSquareRootRemintegerSquareRootRem'exactSquareRootisSquare isSquare'isPossibleSquareisPossibleSquare2 totientSumgeneralInversion integerRoot exactRoot isKthPowerisPerfectPower highestPower largePFPower PrimeSieve primeSieve primeList psieveList psieveFromtrialDivisionTotrialDivisionPrimeToprimeCountMaxArg primeCountnthPrimeMaxArgnthPrimegcdInt coprimeIntgcdWord coprimeWordgcdInt# coprimeInt#gcdWord# coprimeWord# binaryGCD extendedGCDcoprime invertModjacobijacobi'powerMod powerMod'powerModIntegerpowerModInteger'sqrtModP sqrtModPList sqrtModP' tonelliShanks sqrtModPPsqrtModF sqrtModFList sqrtModPPListchineseRemainderchineseRemainder2isPrime millerRabinVisStrongFermatPP isFermatPP bailliePSW factorise factorise'stepFactorisationdefaultStdGenFactorisationdefaultStdGenFactorisation'stdGenFactorisationcurveFactorisationmontgomeryFactorisation smallFactorsCarmichaelSieve TotientSieve FactorSieve factorSieve sieveFactor totientSieve sieveTotientcarmichaelSievesieveCarmichaeltotientφ carmichaelλmoebiusμdivisorstau divisorCount divisorSumdivisorPowerSumsigmaστPrimalityArgumentPockDivisionObvious Assumptionaprime largeFactor smallFactor factorListalimitPrimalityProofcprimeCompositenessArgumentDivisorsFermatLucasBeliefcompo firstDivisor secondDivisor fermatBaseCompositenessProof composite Certificate CompositePrimeargueCertificatearguePrimalityverifyPrimalityArgumentargueCompositenessverifyCompositenessArgumentcheckCertificatecheckCompositenessProofcheckPrimalityProofcertifycertifiedFactorisationcertificateFactorisationprovenFactorisationisCertifiedPrime fsIsPrimeGaussianInteger:+realimagιquotRemGquotGremGdivModGdivGmodG conjugatenormgcdGgcdG' findPrime findPrime'.^$fNumGaussianInteger$fShowGaussianInteger$fEqGaussianIntegerUniqueFactorisationunPrime$$fUniqueFactorisationGaussianInteger$fUniqueFactorisationNatural$fUniqueFactorisationInteger$fUniqueFactorisationWord$fUniqueFactorisationInt$fEqSmallPrime$fOrdSmallPrime$fShowSmallPrime $fEqBigPrime $fOrdBigPrime$fShowBigPrime$fEqGaussianPrime$fShowGaussianPrimeArithmeticFunction runFunctionmultiplicative divisorsA divisorsSmalldivisorsSmallAtauAsigmaAtotientAjordanjordanAmoebiusA liouville liouvilleA carmichaelAadditive smallOmega smallOmegaAbigOmega bigOmegaA expMangoldt expMangoldtAshiftToOddCount shiftOCWordghc-prim GHC.TypesWord shiftOCIntIntshiftOCInteger integer-gmpGHC.Integer.TypeIntegerbigNatZeroCountBigNat shiftToOdd shiftOInt shiftOWord shiftOInteger shiftToOdd#shiftToOddCount# bitCountWord#GHC.PrimWord# bitCountWord bitCountInt trailZeros#uncheckedShiftRsplitOff array-0.5.1.1Data.Array.Base castSTUArray unsafeThaw unsafeFreezeunsafeAtboundsUArray unsafeWrite unsafeReadunsafeNewArray_idxPrtoPrimtoIdxrhoresiduesdeltadeltastausbyte startByteidxstartIdxmunumArrnArrbaseGHC.EnummaxBoundGHC.BasemapGHC.Num fromIntegerGHC.List takeWhileGHC.Real fromIntegralHippEHDelDsteppushbubblemkHippincadjustbuildH simpleSieve feederSievefeedersieve nextIndex wheelPrimesfindIx remaindersstepsappinthApphasBit#power ppTotientppDivSum ppDivPowerSumnewton4 approxBiSqrt appBiSqrt biSqRes256 biSqRes425 biSqRes377 biSqrtInt biSqrtWord biSqrtIgrappCuRt cubeRootInt' cubeRootWord cubeRootIgrnewton3 approxCuRtcr512 cubeRes837 cubeRes637 cubeRes703logArrheronappSqrt karatsubaStepkaratsubaSplitdoubleNothingJust sqRemArraysr256sr819sr4097sr341sr1025sr2047sr693sr325 isqrtInt' isqrtWord isqrtInteger fastInvertabsnewtonK approxKthRoot appKthRootintegerHighPower findHighPowerspBExspBoundsmallOddPrimes finishPowerrawPower rawOddPowerbadPower divisorsTosieveToPS CacheWord sieveBytes sieveBits lastIndex sieveRange sieveWords makeSievesslice growCache countFromToWd countFromTo nthPrimeCt countToNth countDowncountAlltoptrialDivisionWithtrialDivisionPrimeWithtooLowtooHighlowSieve sieveCountcalctreatlocatecopyTocopyRemcp6copcpCtArcpDfArcpGpArInt# gcdWordOdd#oddGCD#absInt#gcdminBoundgi64gw64 binaryGCDImplci64cw64 coprimeImplgcdOddoddGCDgi8gi16gi32gw8gw16gw32ci8ci16ci32cw8cw16cw32modjacPSjacOL powerModImpl powerMod'ImplsqM2PevenIrem4rem8jac2 findNonSquare lucasTest testLucas smallPrimes!random-1.1-54KmMHXjttlERYcr1mvsAe System.RandomStdGenrandomRPointPCurveCmontgomeryDataaddmultiply primeStorelistmergemergeAll testParms findParmsGHC.WordWord16fsBound fsPrimeTestCSTSFSspfSievetotSievecarSieveunFact primProof compProofFalsetrivial maybeTrivialisTrivialPrime trivialPrimes smallCert certifyBPSWfindDecomposition findFactorfindLoop bpswMessagefoundfermat Pocklington TrialDivisionTrivialfactorisedPartcofactor knownFactorstdLimitFactors StrongFermatLucasSelfridge firstFactor secondFactorwitnesstest primeCheckcertiFactorisationinvalidquotremdiv divHelper trialDividecountEvenDivisions GaussianPrime_unGaussianPrimeBigPrime _unBigPrime SmallPrime _unSmallPrime wordToInt wordToInteger intToWord intToIntegernaturalToIntegerintegerToNatural integerToWord Data.MonoidProductSum getProductgetSum$fNumArithmeticFunction$fFloatingArithmeticFunction$fFractionalArithmeticFunction$fMonoidArithmeticFunction$fSemigroupArithmeticFunction$fApplicativeArithmeticFunction$fFunctorArithmeticFunction IntSetProductgetIntSetProduct SetProduct getSetProductXor_getXorLCMgetLCMMangoldt MangoldtZero MangoldtOne MangoldtManyMoebiusMoebiusZMoebiusPMoebiusNdivisorsHelperdivisorsHelperSmall sigmaHelper jordanHelper runMoebius runMangoldtrunXor$fMonoidIntSetProduct$fSemigroupIntSetProduct$fMonoidSetProduct$fSemigroupSetProduct $fMonoidXor$fSemigroupXor $fMonoidLCM$fSemigroupLCM$fMonoidMangoldt$fSemigroupMangoldt$fMonoidMoebius$fSemigroupMoebius