E      !"#$%&'()*+,-./0123456789:;<= > ? @ A B C D E F G H I J K L M N O P Q R S T U VWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#$%&'()*+,-. / 0 1 2 3 4 5 6 7 8!9!:!;!<!=!>!?!@!A!B"CD8#SafeEFGHIJKLMNOPQR(c) 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None &'-DFV5 Point on unknown curve.nWe use the Montgomery form of elliptic curve: b Y = X + a X + X (mod n). See Eq. (10.3.1.1) at p. 260 of  dhttp://www.ams.org/journals/mcom/1987-48-177/S0025-5718-1987-0866113-7/S0025-5718-1987-0866113-7.pdf@Speeding the Pollard and Elliptic Curve Methods of Factorization by P. L. Montgomery.DSwitching to projective space by substitutions Y = y / z, X = x / z, we get b y z = x + a x z + x z (mod n). The point on projective elliptic curve is characterized by three coordinates, but it appears that only x- and z-components matter for computations. By the same reason there is no need to store coefficient b.That said, the chosen curve is represented by a24 = (a + 2) / 4 and modulo n at type level, making points on different curves incompatible.Extract x-coordinate.Extract z-coordinate.   s n- creates a point on an elliptic curve modulo n, uniquely determined by seed s. Some choices of s and nE produce ill-parametrized curves, which is reflected by return value S.KWe choose a curve by Suyama's parametrization. See Eq. (3)-(4) at p. 4 of  9http://www.hyperelliptic.org/tanja/SHARCS/talks06/Gaj.pdfNImplementing the Elliptic Curve Method of Factoring in Reconfigurable Hardware by K. Gaj, S. Kwon et al. If p0 + p1 = p2, then   p0 p1 p2 equals to p1 + p2-. It is also required that z-coordinates of p0, p1 and p2A are coprime with modulo of elliptic curve; and x-coordinate of p0G is non-zero. If preconditions do not hold, return value is undefined.*Remarkably such addition does not require  a24 constraint.,Computations follow Algorithm 3 at p. 4 of  9http://www.hyperelliptic.org/tanja/SHARCS/talks06/Gaj.pdfNImplementing the Elliptic Curve Method of Factoring in Reconfigurable Hardware by K. Gaj, S. Kwon et al. Multiply by 2.,Computations follow Algorithm 3 at p. 4 of  9http://www.hyperelliptic.org/tanja/SHARCS/talks06/Gaj.pdfNImplementing the Elliptic Curve Method of Factoring in Reconfigurable Hardware by K. Gaj, S. Kwon et al. 1Multiply by given number, using binary algorithm. For debugging.In projective space Cs are equal, if they are both at infinity or if respective ratios  /  are equal.   T(c) 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None &'-0FKQV]`This type represents residues with unknown modulo and rational numbers. One can freely combine them in arithmetic expressions, but each operation will spend time on modulo's recalculation: > 2 `modulo` 10 + 4 `modulo` 15 (1 `modulo` 5) > 2 `modulo` 10 * 4 `modulo` 15 (3 `modulo` 5) > 2 `modulo` 10 + fromRational (3 % 7) (1 `modulo` 10) > 2 `modulo` 10 * fromRational (3 % 7) (8 `modulo` 10)8If performance is crucial, it is recommended to extract Mod m4 for further processing by pattern matching. E. g., fcase modulo n m of SomeMod k -> process k -- Here k has type Mod m InfMod{} -> error "impossible"Wrapper for residues modulo m.Mod 3 :: Mod 10 stands for the class of integers, congruent to 3 modulo 10 ( &"17, "7, 3, 13, 23 &). The modulo is stored on type level, so it is impossible, for example, to add up by mistake residues with different moduli. p> (3 :: Mod 10) + (4 :: Mod 12) error: Couldn't match type 12  with 10 ... > (3 :: Mod 10) + 8 (1 `modulo` 10)$Note that modulo cannot be negative..Linking type and value levels: extract modulo m as a value..Linking type and value levels: extract modulo m as a value.HThe canonical representative of the residue class, always between 0 and m-1 inclusively.HThe canonical representative of the residue class, always between 0 and m-1 inclusively.HComputes the modular inverse, if the residue is coprime with the modulo. o> invertMod (3 :: Mod 10) Just (7 `modulo` 10) -- because 3 * 7 = 1 :: Mod 10 > invertMod (4 :: Mod 10) NothingDrop-in replacement for H, with much better performance. (> powMod (3 :: Mod 10) 4 (1 `modulo` 10)Infix synonym of .Create modular value by representative of residue class and modulo. One can use the result either directly (via functions from U and V5), or deconstruct it by pattern matching. Note that  never returns .)Computes the inverse value, if it exists. > invertSomeMod (3 `modulo` 10) Just (7 `modulo` 10) -- because 3 * 7 = 1 :: Mod 10 > invertMod (4 `modulo` 10) Nothing > invertSomeMod (fromRational (2 % 5)) Just 5 % 2Drop-in replacement for H`, with much better performance. When -O is enabled, there is a rewrite rule, which specialises H to . .> powSomeMod (3 `modulo` 10) 4 (1 `modulo` 10)uBeware that division by residue, which is not coprime with the modulo, will result in runtime error. Consider using  instead."uBeware that division by residue, which is not coprime with the modulo, will result in runtime error. Consider using  instead.W87(c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None<Db)**)$(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalportableSafek+Following 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.+,-.%(c) 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)SafeFTo/6Type of primes of a given unique factorisation domain.abs (unPrime n) == unPrime n must hold for all n of type Prime t/XYZ[\]XYZ[\](c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)Safep0(Infinite zero-based table of factorials. > take 5 factorial [1,1,2,6,24] The time-and-space behaviour of 0 is similar to described in .Math.NumberTheory.Recurrencies.Bilinear#memory.11 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.22 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.33 k computes the k%-th Lucas number. Very similar to 1.44 k computes the pair (L(k), L(k+1)) of the k7-th Lucas number and its successor. Very similar to 2.55 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.012345012345(c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)Safe56UInfinite zero-based table of binomial coefficients (also known as Pascal triangle): (binomial !! n !! k == n! / k! / (n - k)!. J> take 5 (map (take 5) binomial) [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] Complexity: binomial !! n !! kI is O(n) bits long, its computation takes O(k n) time and forces thunks binomial !! n !! i for  0 <= i <= k'. Use the symmetry of Pascal triangle .binomial !! n !! k == binomial !! n !! (n - k) to speed up computations.One could also consider &' to compute stand-alone values.7Infinite zero-based table of  @https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind"Stirling numbers of the first kind. L> take 5 (map (take 5) stirling1) [[1],[0,1],[0,1,1],[0,2,3,1],[0,6,11,6,1]] Complexity: stirling1 !! n !! kU is O(n ln n) bits long, its computation takes O(k n^2 ln n) time and forces thunks stirling1 !! i !! j for  0 <= i <= n and max(0, k - n + i) <= j <= k.One could also consider &( to compute stand-alone values.8Infinite zero-based table of  Ahttps://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind#Stirling numbers of the second kind. K> take 5 (map (take 5) stirling2) [[1],[0,1],[0,1,1],[0,1,3,1],[0,1,7,6,1]] Complexity: stirling2 !! n !! kU is O(n ln n) bits long, its computation takes O(k n^2 ln n) time and forces thunks stirling2 !! i !! j for  0 <= i <= n and max(0, k - n + i) <= j <= k.One could also consider &) to compute stand-alone values.9Infinite one-based table of  (https://en.wikipedia.org/wiki/Lah_number Lah numbers.  lah !! n !! k equals to lah(n + 1, k + 1). O> take 5 (map (take 5) lah) [[1],[2,1],[6,6,1],[24,36,12,1],[120,240,120,20,1]] Complexity:  lah !! n !! kS is O(n ln n) bits long, its computation takes O(k n ln n) time and forces thunks  lah !! n !! i for  0 <= i <= k.:Infinite zero-based table of  -https://en.wikipedia.org/wiki/Eulerian_number"Eulerian numbers of the first kind. D> take 5 (map (take 5) eulerian1) [[],[1],[1,1],[1,4,1],[1,11,11,1]] Complexity: eulerian1 !! n !! kU is O(n ln n) bits long, its computation takes O(k n^2 ln n) time and forces thunks eulerian1 !! i !! j for  0 <= i <= n and max(0, k - n + i) <= j <= k.;Infinite zero-based table of  Qhttps://en.wikipedia.org/wiki/Eulerian_number#Eulerian_numbers_of_the_second_kind#Eulerian numbers of the second kind. E> take 5 (map (take 5) eulerian2) [[],[1],[1,2],[1,8,6],[1,22,58,24]] Complexity: eulerian2 !! n !! kU is O(n ln n) bits long, its computation takes O(k n^2 ln n) time and forces thunks eulerian2 !! i !! j for  0 <= i <= n and max(0, k - n + i) <= j <= k.< Infinite zero-based sequence of  .https://en.wikipedia.org/wiki/Bernoulli_numberBernoulli numbers, computed via  bhttps://en.wikipedia.org/wiki/Bernoulli_number#Connection_with_Stirling_numbers_of_the_second_kind connection with 8. 9> take 5 bernoulli [1 % 1,(-1) % 2,1 % 6,0 % 1,(-1) % 30] Complexity: bernoulli !! nS is O(n ln n) bits long, its computation takes O(n^3 ln n) time and forces thunks stirling2 !! i !! j for  0 <= i <= n and  0 <= j <= i.One could also consider &* to compute stand-alone values.6789:;<6789:;<+(c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNone ^_`abcdef,(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None; ghijklmnop (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None=fA list of primes. The sieve does not handle overflow, hence for bounded types, garbage occurs near q,. If primes that large are requested, use  r s $ t (<= u q) = Pinstead. Checking for overflow would be slower. The sieve is specialised for v, w and xA, 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.=>=>yz{|} (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None<D ?: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.ACalculate 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.BCalculate 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.CReturns S% 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 F.DXTest whether the argument is a square. After a number is found to be positive, first F@ is checked, if it is, the integer square root is calculated.E.Test whether the input (a nonnegative number) n is a square. The same as DW, 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.FTest 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 C@. For large numbers, the slower but more discriminating test isPossibleSqure2 is faster.GTest 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 F, 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). ?@ABCDEFG ?@ABCDEFG (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None<DH[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.I[Calculate the integer fourth root of a nonnegative number, that is, the largest integer r with r^4 <= n. The condition is not checked.JReturns Nothing if n is not a fourth power, Just r if n == r^4 and r >= 0.KsTest whether an integer is a fourth power. First nonnegativity is checked, then the unchecked test is called.LITest whether a nonnegative number is a fourth power. The condition is not$ checked. If a number passes the M0 test, its integer fourth root is calculated.MRTest whether a nonnegative number is a possible fourth power. The condition is not6 checked. This eliminates about 99.958% of numbers.HIJKLMHIJKLM (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None<D N.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.O9Calculate 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.PReturns Nothing# if the argument is not a cube, Just r if n == r^3.Q"Test whether an integer is a cube.R8Test whether a nonnegative integer is a cube. Before N 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.S}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.Happroximate cube root, about 50 bits should be correct for large numbersNOPQRSNOPQRS (c) 2012 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None<AT totientSum n is, for n > 0 , the sum of otient k | k <- [1 .. n]]7, computed via generalised Mbius inversion. See  :http://mathworld.wolfram.com/TotientSummatoryFunction.html for the formula used for  totientSum.UgeneralInversion g n/ evaluates the generalised Mbius inversion of g at the argument n.xThe generalised Mbius 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]] Jcan be cheaply computed. By the generalised Mbius 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 Mbius function are known. A slightly different formula, used here, does not need the values of the Mbius 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 v 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.TUUT(c) 2012 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None<aV totientSum n is, for n > 0 , the sum of otient k | k <- [1 .. n]]7, computed via generalised Mbius inversion. See  :http://mathworld.wolfram.com/TotientSummatoryFunction.html for the formula used for  totientSum.WgeneralInversion g n/ evaluates the generalised Mbius inversion of g at the argument n.xThe generalised Mbius 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]] Jcan be cheaply computed. By the generalised Mbius 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 Mbius function are known. A slightly different formula, used here, does not need the values of the Mbius 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 v. 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.VWWV-(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneDxRemove 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 w<. Precondition: argument strictly positive (not checked).Specialised version for v2. Precondition: argument nonzero (not checked).Specialised version for x2. 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 v2. Precondition: argument nonzero (not checked).Specialised version for w2. Precondition: argument nonzero (not checked).Specialised version for v2. 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 w.Number of 1-bits in an v.Number of trailing zeros in a  , wrong for 0.3It is difficult to convince GHC to unbox output of  and  'splitOff.go'K, so we fallback to a specialized unboxed version to minimize allocations. .(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None<sX!Compact store of primality flags.YSieve 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 v<-indexed, overflow occurs when the sieve size comes near q :: v-, that corresponds to an upper bound near 15/8*q. On 32Y-bit systems, that is often within memory limits, so don't give bounds larger than 8*10^9 there.Z4Generate a list of primes for consumption from a X.[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 Xs, more compact than [, thus it may be better to use \ >>= Z@ 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 Xs 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 [x]B, hence it may be preferable to use this if it is to be reused.XYZ[\]^X(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneXYZ[\]^[]XY\^Z(c) 2018 Frederick SchneiderMIT7Frederick Schneider <frederick.schneider2011@gmail.com> ProvisionalNon-portable (GHC extensions)None_ZAn abstract representation of a smooth basis. It consists of a set of coprime numbers "e2.`Build a _" from a set of coprime numbers "e2. > fromSet (Set.fromList [2, 3]) Just (SmoothBasis [2, 3]) > fromSet (Set.fromList [2, 4]) -- should be coprime Nothing > fromSet (Set.fromList [1, 3]) -- should be >= 2 NothingaBuild a _# from a list of coprime numbers "e2. > fromList [2, 3] Just (SmoothBasis [2, 3]) > fromList [2, 2] Just (SmoothBasis [2]) > fromList [2, 4] -- should be coprime Nothing > fromList [1, 3] -- should be >= 2 NothingbBuild a _) from a list of primes below given bound. Z> fromSmoothUpperBound 10 Just (SmoothBasis [2, 3, 5, 7]) > fromSmoothUpperBound 1 Nothingc(Generate an infinite ascending list of  +https://en.wikipedia.org/wiki/Smooth_numbersmooth numbers over a given smooth basis. W> take 10 (smoothOver (fromJust (fromList [2, 5]))) [1, 2, 4, 5, 8, 10, 16, 20, 25, 32]dGenerate an ascending list of  +https://en.wikipedia.org/wiki/Smooth_numbersmooth numbers- over a given smooth basis in a given range.JIt may appear inefficient for short, but distant ranges; consider using e in such cases. R> smoothOverInRange (fromJust (fromList [2, 5])) 100 200 [100, 125, 128, 160, 200]eGenerate an ascending list of  +https://en.wikipedia.org/wiki/Smooth_numbersmooth numbers- over a given smooth basis in a given range.HIt is inefficient for large or starting near 0 ranges; consider using d in such cases.MSuffix BF stands for the brute force algorithm, involving a lot of divisions. T> smoothOverInRangeBF (fromJust (fromList [2, 5])) 100 200 [100, 125, 128, 160, 200]oisValid assumes that the list is sorted and unique and then checks if the list is suitable to be a SmoothBasis._`abcde_`abcde_/(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> Provisional non-portableNone<gMaximal allowed argument of h. Currently 8e18.hh 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 g. Requires O(n^0.5)' space, the time complexity is roughly O(n^0.7). For small bounds, h 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.iMaximal allowed argument of j. Currently 1.5e17.jj n calculates the n%-th prime. Numbering of primes is 1 -based, so j 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 i.ghij(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> Provisional non-portableNone}+,-.ghijhgji,+.-0(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)Nonem Factorise an x 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.kk 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).ll 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.kl(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneDymCalculate an integer root, m k n computes the (floor of) the k-th root of n, where k must be positive. r = m 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, m 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.nn k n returns S 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.oo k n checks whether n is a k -th power.pp n checks whether n == r^k for some k > 1.qq n produces the pair (b,k) with the largest exponent k such that n == b^k , except for  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.rr 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 q0 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.mnopqrmnopqr/(c) 2011 Daniel Fischer, 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None]sType for result of w.wgJacobi 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.xLJacobi symbol of two numbers without validity check of the "denominator".svutwxstuvwxstuv1/(c) 2011 Daniel Fischer, 2017 Andrew LelechenkoMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneDA~ isPrime n tests whether nb is a prime (negative or positive). It is a combination of trial division and Baillie-PSW test.If  isPrime n returns False then nE is definitely composite. There is a theoretical possibility that  isPrime n is True, but in fact nJ is not prime. However, no such numbers are known and none exist below 2^64N. If you have found one, please report it, because it is a major discovery.Miller-Rabin probabilistic primality test. It consists of the trial division test and several rounds of the strong Fermat test with different bases. The choice of trial divisors and bases are implementation details and may change in future silently.yFirst argument stands for the number of rounds of strong Fermat test. If it is 0, only trial division test is performed.If millerRabinV k n returns False then n% is definitely composite. Otherwise n' may appear composite with probability 1/4^k. n b tests whether non-negative n/ is a strong Fermat probable prime for base b.'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  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.Please consult  https://miller-rabin.appspot.com9Deterministic variants of the Miller-Rabin primality test! for the best choice of bases. 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 ( 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).Primality 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.~(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneDLGreatest common divisor of two v,s, calculated with the binary gcd algorithm.Test whether two v9s are coprime, using an abbreviated binary gcd algorithm.Greatest common divisor of two w,s, calculated with the binary gcd algorithm.Test whether two w9s 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)NoneD]q#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 v and w$ 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 x\ (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.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 23) 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).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.The input list is assumed to be a factorisation of some number into a list of powers of (possibly, composite) non-zero factors. The output list is a factorisation of the same number such that all factors are coprime. Such transformation is crucial to continue factorisation (lazily, in parallel or concurrent fashion) without having to merge multiplicities of primes, which occurs more than in one composite factor. > splitIntoCoprimes [(140, 1), (165, 1)] [(5,2),(28,1),(33,1)] > splitIntoCoprimes [(360, 1), (210, 1)] [(2,4),(3,3),(5,2),(7,1)]4(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None-FV]/  n% produces the prime factorisation of n, including a factor of (-1) if n < 0.  0) is an error and the factorisation of 1 is empty. Uses a < produced in an arbitrary manner from the bit-pattern of n.Like $, but without input checking, hence n > 1 is required. is like , 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. 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.Like $, but without input checking, so n must be larger than 1.A wrapper around = providing a few default arguments. The primality test is , the prng function - naturally - R. This function also requires small prime factors to have been stripped before. 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. n1 requires that small (< 100000) prime factors of n^ have been stripped before. Otherwise it is likely to cycle forever. When in doubt, use . is unlikely to succeed if n/ has more than one (really) large prime factor. 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.7The implementation follows the algorithm at p. 6-7 of  9http://www.hyperelliptic.org/tanja/SHARCS/talks06/Gaj.pdfNImplementing the Elliptic Curve Method of Factoring in Reconfigurable Hardware by K. Gaj, S. Kwon et al.^Same as map (id *** flip multiply p) [from, thn .. to], but calculated in more efficient way. 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.For a given estimated decimal length of the smallest prime factor ("tier") return parameters B1, B2 and the number of curves to try before next "tier". Roughly based on `http://www.mersennewiki.org/index.php/Elliptic_Curve_Method#Choosing_the_best_parameters_for_ECM"Lower bound for composite divisors Standard PRNG3Estimated number of digits of smallest prime factorThe number to factorise#List of prime factors and exponents"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 exponents 5(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 x. 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 failure3  6(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)None#/7(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None<V/5A compact store of values of the Carmichael function.A compact store of totients.*A compact store of smallest prime factors. 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. fs n" finds the prime factorisation of n using the  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 + only stores values for numbers coprime to 30< to reduce space usage. The maximal admissible value for n is u (q :: w). 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  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.7Calculate the totient from the canonical factorisation.Totient of a prime power. nS creates a store of values of the Carmichael function for numbers not exceeding n . Like a , a + only stores values for numbers coprime to 30< to reduce space usage. The maximal admissible value for n is u (q :: w). 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 .{Calculate the Carmichael function from the factorisation. Requires that the list of prime factors is strictly ascending. (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None3oTest primality using a . If n0 is out of bounds of the sieve, fall back to ~. l~ ~l(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneN  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 ; 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 &, 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)NoneQkk8(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneS*+,-.XYZ[\]^ghijkl~(c) 2011 Daniel FischerMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None\ 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.%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 FischerMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None}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.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 positive 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 primesqrtModF 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.sqrtModFList 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.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.9(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None\svutwx:(c) 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)Safe(c) 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)NoneDpowMod b e m computes (b^e) `mod` m in effective way. An exponent e must be non-negative, a modulo m/ must be positive. Otherwise the behaviour of powMod is undefined. 7> powMod 2 3 5 3 > powMod 3 12345678901234567890 1001 1 See also ; and <.For finite numeric types (v, w, etc.) modulo m should be such that m^2 does not overflow, otherwise the behaviour is undefined. If you need both to fit into machine word and to handle large moduli, take a look at  and . > powMod 3 101 (2^60-1 :: Integer) 1018105167100379328 -- correct > powMod 3 101 (2^60-1 :: Int64) 1115647832265427613 -- incorrect due to overflow > powModInt 3 101 (2^60-1 :: Int) 1018105167100379328 -- correctSpecialised version of (, able to handle large moduli correctly. /> powModWord 3 101 (2^60-1) 1018105167100379328Specialised version of (, able to handle large moduli correctly. .> powModInt 3 101 (2^60-1) 1018105167100379328=(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None?CDHJKNPQmnopq?DCNQPHKJmonpq'(c) 2016 Chris Fredrickson, Google Inc.MIT1Chris 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)NoneFT&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.//(c) 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)NoneFTA container for a number and its pairwise coprime (but not neccessarily prime) factorisation. It is designed to preserve information about factors under multiplication. One can use this representation to speed up prime factorisation and computation of arithmetic functions.For instance, let p and q be big primes: i> let p, q :: Integer > p = 1000000000000000000000000000057 > q = 2000000000000000000000000000071PIt would be difficult to compute prime factorisation of their product as is: H would take ages. Things become different if we simply change types of p and q to prefactored ones: u> let p, q :: Prefactored Integer > p = 1000000000000000000000000000057 > q = 2000000000000000000000000000071*Now prime factorisation is done instantly: > factorise (p * q) [(PrimeNat 1000000000000000000000000000057, 1), (PrimeNat 2000000000000000000000000000071, 1)] > factorise (p^2 * q^3) [(PrimeNat 1000000000000000000000000000057, 2), (PrimeNat 2000000000000000000000000000071, 3)]#Moreover, we can instantly compute totient7 and its iterations. It works fine, because output of totient is also prefactored. }> prefValue $ totient (p^2 * q^3) 8000000000000000000000000001752000000000000000000000000151322000000000000000000000006445392000000000000000000000135513014000000000000000000001126361040 > prefValue $ totient $ totient (p^2 * q^3) 2133305798262843681544648472180210822742702690942899511234131900112583590230336435053688694839034890779375223070157301188739881477320529552945446912000Let us look under the hood: > prefFactors $ totient (p^2 * q^3) [(2, 4), (41666666666666666666666666669, 1), (3, 3), (111111111111111111111111111115, 1), (1000000000000000000000000000057, 1), (2000000000000000000000000000071, 2)] > prefFactors $ totient $ totient (p^2 * q^3) [(2, 22), (39521, 1), (5, 3), (199937, 1), (3, 8), (6046667, 1), (227098769, 1), (85331809838489, 1), (361696272343, 1), (22222222222222222222222222223, 1), (41666666666666666666666666669, 1), (2000000000000000000000000000071, 1)]Pairwise coprimality of factors is crucial, because it allows us to process them independently, possibly even in parallel or concurrent fashion.*Following invariant is guaranteed to hold: Eabs (prefValue x) = abs (product (map (uncurry (^)) (prefFactors x)))Number itself.cList of pairwise coprime (but not neccesarily prime) factors, accompanied by their multiplicities.Create  from a given number. G> fromValue 123 Prefactored {prefValue = 123, prefFactors = [(123, 1)]}Create  from a given list of pairwise coprime (but not neccesarily prime) factors with multiplicities. If you cannot ensure coprimality, use . > fromFactors (splitIntoCoprimes [(140, 1), (165, 1)]) Prefactored {prefValue = 23100, prefFactors = [(5, 2), (28, 1), (33, 1)]} > fromFactors (splitIntoCoprimes [(140, 2), (165, 3)]) Prefactored {prefValue = 88045650000, prefFactors = [(5, 5), (28, 2), (33, 3)]}>(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) 2018 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None >?DFT($Represents three possible values of  -https://en.wikipedia.org/wiki/Mbius_functionMbius function."101Convert to any numeric type. 5Evaluate the Mbius function over a block. Value of f. at 0, if zero falls into block, is undefined.,Based on the sieving algorithm from p. 3 of  $https://arxiv.org/pdf/1610.08551.pdfRComputations of the Mertens function and improved bounds on the Mertens conjecture1 by G. Hurst. It is approximately 5x faster than !?. }> sieveBlockMoebius 1 10 [MoebiusP, MoebiusN, MoebiusN, MoebiusZ, MoebiusN, MoebiusP, MoebiusN, MoebiusZ, MoebiusZ, MoebiusP]  @(c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None%FTVYCreate a multiplicative function from the function on prime's powers. See examples below.2The set of all (positive) divisors of an argument.VThe unsorted list of all (positive) divisors of an argument, produced in lazy fashion.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 Mbius 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.! !"#$%&'()*+,-(c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None$ !"#$%&'()*+,-$ !"#$'()*+%&,- (c) 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None0<N]4 .SA multiplicative group of residues is called cyclic, if there is a primitive root g|, whose powers generates all elements. Any cyclic multiplicative group of residues falls into one of the following cases./Residues modulo 2.0Residues modulo 4.1Residues modulo p^k for odd prime p.2Residues modulo 2p^k for odd prime p.3wCheck whether a multiplicative group of residues, characterized by its modulo, is cyclic and, if yes, return its form. > cyclicGroupFromModulo 4 Just CG4 > cyclicGroupFromModulo (2 * 13 ^ 3) Just (CGDoubleOddPrimePower (PrimeNat 13) 3) > cyclicGroupFromModulo (4 * 13) Nothing4UExtract modulo and its factorisation from a cyclic multiplicative group of residues. > cyclicGroupToModulo CG4 Prefactored {prefValue = 4, prefFactors = [(2, 2)]} > cyclicGroupToModulo (CGDoubleOddPrimePower (PrimeNat 13) 3) Prefactored {prefValue = 4394, prefFactors = [(2, 1), (13, 3)]}55 cg a checks whether a is a  5https://en.wikipedia.org/wiki/Primitive_root_modulo_nprimitive root5 of a given cyclic multiplicative group of residues cg. a> let Just cg = cyclicGroupFromModulo 13 > isPrimitiveRoot cg 1 False > isPrimitiveRoot cg 2 True6,Check whether a given modular residue is a  5https://en.wikipedia.org/wiki/Primitive_root_modulo_nprimitive root. J> isPrimitiveRoot (1 :: Mod 13) False > isPrimitiveRoot (2 :: Mod 13) True(Here is how to list all primitive roots: > filter isPrimitiveRoot [minBound .. maxBound] :: [Mod 13] [(2 `modulo` 13), (6 `modulo` 13), (7 `modulo` 13), (11 `modulo` 13)]-This function is a convenient wrapper around 5H. The latter provides better control and performance, if you need them. ./0123456 6./012345./012A(c) 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)NoneDVH~8>A record, which specifies a function to evaluate over a block.>For example, here is a configuration for the totient function: SieveBlockConfig { sbcEmpty = 1 , sbcFunctionOnPrimePower = (\p a -> (p - 1) * p ^ (a - 1) , sbcAppend = (*) }:value of a function on 1;*how to evaluate a function on prime powers<8how to combine values of a function on coprime arguments=RCreate a config for a multiplicative function from its definition on prime powers.>MCreate a config for an additive function from its definition on prime powers.?TEvaluate a function over a block in accordance to provided configuration. Value of f. at 0, if zero falls into block, is undefined.Based on Algorithm M of  #https://arxiv.org/pdf/1305.1639.pdf\Parity of the number of primes in a given interval and algorithms of the sublinear summation by A. V. Lelechenko. See Lemma 2 on p. 5 on its algorithmic complexity. For the majority of use-cases its time complexity is O(x^(1+)).5For example, here is an analogue of divisor function tau: W> sieveBlockUnboxed (SieveBlockConfig 1 (*) (\_ a -> a + 1) 1 10) [1,2,2,3,2,4,2,4,3,4]89:;<=>?89:;<!(c) 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)NoneDV^-@@ f x l8 evaluates an arithmetic function for integers between x and x+l-1 and returns a vector of length ld. It completely avoids factorisation, so it is asymptotically faster than pointwise evaluation of f. Value of f. at 0, if zero falls into block, is undefined.vBeware that for underlying non-commutative monoids the results may potentially differ from pointwise application via .This is a thin wrapper over A, read more details there. => runFunctionOverBlock carmichaelA 1 10 [1,1,2,2,4,2,6,2,6,4]ATEvaluate a function over a block in accordance to provided configuration. Value of f. at 0, if zero falls into block, is undefined.Based on Algorithm M of  #https://arxiv.org/pdf/1305.1639.pdf\Parity of the number of primes in a given interval and algorithms of the sublinear summation by A. V. Lelechenko. See Lemma 2 on p. 5 on its algorithmic complexity. For the majority of use-cases its time complexity is O(x^(1+)).A is similar to ? up to flavour of BCa, but is typically 7x-10x slower and consumes 3x memory. Use unboxed version whenever possible.9For example, following code lists smallest prime factors: T> sieveBlock (SieveBlockConfig maxBound min (\p _ -> p) 2 10) [2,3,2,5,2,7,2,3,2,11]  89:;<=>?@A @89:;<=>A? "(c) 2018 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None]gBKCompute individual values of Mertens function in O(n^(2/3)) time and space. E> map (mertens . (10 ^)) [0..9] [1,-1,1,2,-23,-48,212,1037,1928,-222],The implementation follows Theorem 3.1 from  $https://arxiv.org/pdf/1610.08551.pdfRComputations of the Mertens function and improved bounds on the Mertens conjecture/ by G. Hurst, excluding segmentation of sieves.0Compute sum (map (x -> runMoebius (mu x) * f x))BBD(c) 2018 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None]sg $Straightforward computation of [ n x x | x <- [hi, hi - 1 .. lo] ]. Unfortunately, such list generator performs poor, so we fall back to manual recursion. 0bresenham(x+1) -> bresenham(x) for x >= (2n)^1/3 "Division-free computation of [ n v x | x <- [hi, hi - 1 .. lo] ]. In other words, we compute y-coordinates of highest integral points under hyperbola  x * y = n between x = lo and x = hi in reverse order.(The implementation follows section 5 of  #https://arxiv.org/pdf/1206.3369.pdfQA successive approximation algorithm for computing the divisor summatory functionD by R. Sladkey. It is 2x faster than a trivial implementation for v.   (c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)SafeVC\Infinite sequence of exact values of Riemann zeta-function at even arguments, starting with (0)5. Note that due to numerical errors convertation to  may return values below 1: A> approximateValue (zetasEven !! 25) :: Double 0.9999999999999996DUse your favorite type for long-precision arithmetic. For instance, EF works fine: i> approximateValue (zetasEven !! 25) :: Fixed Prec50 1.00000000000000088817842111574532859293035196051773D~Infinite sequence of approximate (up to given precision) values of Riemann zeta-function at integer arguments, starting with (0)B. Computations for odd arguments are performed in accordance to  %https://cr.yp.to/bib/2000/borwein.pdf6Computational strategies for the Riemann zeta function@ by J. M. Borwein, D. M. Bradley, R. E. Crandall, formula (57). k> take 5 (zetas 1e-14) :: [Double] [-0.5,Infinity,1.6449340668482262,1.2020569031595942,1.0823232337111381]Beware to force evaluation of  zetas !! 1, if the type a2 does not support infinite values (for instance, EF).CDDCGHIJKLMMNOPQRSTUVWXYZZ[\]^_`a;bcd<efghijklmnopq$r$s$t$u%vwxyz{|'}~* .......////001111144444444455555555555555555555555555v5555555556777777777     ; !"#$%&'()*+,-./0123456789:>;>;><=>?@ABCDEFGHIJ@K@L@M@N@O@P@Q@R@S@T@U@V@W@X@Y@Z@[@\@]@^@_@`@a@b@c@d@e@f g h i j k l m n o pAqAqArAsAtAuAvA?!w!x"yz{|}~GHGHGHGHGHGHGHGHGHGHGHGHGHGNGG\%%%%%%,,,,,,R,,,,GGGGG|}|}     G ------------|------..........00GG1|GG4444444455|}555555555555555555555555 5 G  7 7777777:::::: :!G"G#G$%%&3G'(G')G'*G'+>,-./0@1@1@2@3@3@4@5@5@6@7@7@8@9@9@:@;@<@=@>"?D@DADBDCDCDDDEDFDGDH|}IJ&arithmoi-0.7.0.0-oN9220ftkhDqxe7jKH1U6Math.NumberTheory.Moduli.ClassMath.NumberTheory.Zeta#Math.NumberTheory.Curves.Montgomery)Math.NumberTheory.Powers.Squares.Internal!Math.NumberTheory.Primes.Counting%Math.NumberTheory.UniqueFactorisation%Math.NumberTheory.Recurrencies.Linear'Math.NumberTheory.Recurrencies.BilinearMath.NumberTheory.Primes.Heap Math.NumberTheory.Powers.SquaresMath.NumberTheory.Powers.FourthMath.NumberTheory.Powers.Cubes&Math.NumberTheory.MoebiusInversion.Int"Math.NumberTheory.MoebiusInversionMath.NumberTheory.Primes.SieveMath.NumberTheory.SmoothNumbers&Math.NumberTheory.Primes.Factorisation Math.NumberTheory.Primes.Testing Math.NumberTheory.Powers.GeneralMath.NumberTheory.Moduli.JacobiMath.NumberTheory.GCD.LowLevelMath.NumberTheory.GCD-Math.NumberTheory.Primes.Testing.Certificates0Math.NumberTheory.Primes.Factorisation.Certified Math.NumberTheory.Moduli.ChineseMath.NumberTheory.Moduli.Sqrt Math.NumberTheory.Powers.Modular"Math.NumberTheory.GaussianIntegersMath.NumberTheory.Prefactored%Math.NumberTheory.ArithmeticFunctions-Math.NumberTheory.ArithmeticFunctions.Moebius&Math.NumberTheory.Moduli.PrimitiveRoot0Math.NumberTheory.ArithmeticFunctions.SieveBlock-Math.NumberTheory.ArithmeticFunctions.MertensGHC.TypeNats.Compat-Math.NumberTheory.Primes.Counting.ApproximateMath.NumberTheory.Primes.TypesMath.Combinat.NumbersbinomialunsignedStirling1st stirling2nd bernoulliMath.NumberTheory.Unsafe'Math.NumberTheory.Primes.Sieve.IndexingMath.NumberTheory.Utils+Math.NumberTheory.Primes.Sieve.Eratosthenes&Math.NumberTheory.Primes.Counting.Impl4Math.NumberTheory.Primes.Factorisation.TrialDivision.Math.NumberTheory.Primes.Testing.ProbabilisticNumeric.NaturalNatural1Math.NumberTheory.Primes.Factorisation.Montgomery6Math.NumberTheory.Primes.Testing.Certificates.Internal*Math.NumberTheory.Primes.Testing.Certified#Math.NumberTheory.Primes.Sieve.MiscMath.NumberTheory.PrimesMath.NumberTheory.Moduli$Math.NumberTheory.Utils.FromIntegralpowMod powSomeModMath.NumberTheory.Powers+Math.NumberTheory.ArithmeticFunctions.ClasssieveBlockUnboxed.Math.NumberTheory.ArithmeticFunctions.Standard8Math.NumberTheory.ArithmeticFunctions.SieveBlock.UnboxedDataVector!Math.NumberTheory.Utils.HyperbolaData.Number.FixedFixedbase GHC.TypeNatsKnownNat'exact-pi-0.4.1.3-9n9GqWDBnkQAVoDnNmzltw Data.ExactPiapproximateValue SomePointPointpointXpointZpointA24pointNnewPointadddoublemultiply $fShowPoint $fEqPoint$fShowSomePointSomeModInfModModgetMod getNatModgetVal getNatVal invertMod^%modulo invertSomeMod$fFractionalMod$fNumMod $fBoundedMod $fShowMod$fFractionalSomeMod $fNumSomeMod $fShowSomeMod $fEqSomeMod$fEqMod$fOrdMod $fEnumModisqrtA karatsubaSqrt!approxPrimeCountOverestimateLimitapproxPrimeCount nthPrimeApproxUnderestimateLimitnthPrimeApproxPrime factorial fibonacci fibonacciPairlucas lucasPair generalLucas stirling1 stirling2lah eulerian1 eulerian2primes sieveFromintegerSquareRootintegerSquareRoot'integerSquareRootRemintegerSquareRootRem'exactSquareRootisSquare isSquare'isPossibleSquareisPossibleSquare2integerFourthRootintegerFourthRoot'exactFourthRoot isFourthPowerisFourthPower'isPossibleFourthPowerintegerCubeRootintegerCubeRoot' exactCubeRootisCubeisCube'isPossibleCube totientSumgeneralInversion PrimeSieve primeSieve primeList psieveList psieveFrom SmoothBasisfromSetfromListfromSmoothUpperBound smoothOversmoothOverInRangesmoothOverInRangeBF$fShowSmoothBasisprimeCountMaxArg primeCountnthPrimeMaxArgnthPrimetrialDivisionTotrialDivisionPrimeTo integerRoot exactRoot isKthPowerisPerfectPower highestPower largePFPower JacobiSymbolMinusOneZeroOnejacobijacobi'$fMonoidJacobiSymbol$fSemigroupJacobiSymbol$fEqJacobiSymbol$fOrdJacobiSymbol$fShowJacobiSymbolisPrime millerRabinVisStrongFermatPP isFermatPP bailliePSWgcdInt coprimeIntgcdWord coprimeWordgcdInt# coprimeInt#gcdWord# coprimeWord# binaryGCD extendedGCDcoprimesplitIntoCoprimes factorise factorise'stepFactorisationdefaultStdGenFactorisationdefaultStdGenFactorisation'stdGenFactorisationcurveFactorisationmontgomeryFactorisation smallFactorsPrimalityArgumentPockDivisionObvious Assumptionaprime largeFactor smallFactor factorListalimitPrimalityProofcprimeCompositenessArgumentDivisorsFermatLucasBeliefcompo firstDivisor secondDivisor fermatBaseCompositenessProof composite Certificate CompositeargueCertificatearguePrimalityverifyPrimalityArgumentargueCompositenessverifyCompositenessArgumentcheckCertificatecheckCompositenessProofcheckPrimalityProofcertifyisCertifiedPrimeCarmichaelSieve TotientSieve FactorSieve factorSieve sieveFactor totientSieve sieveTotientcarmichaelSievesieveCarmichael fsIsPrimecertifiedFactorisationcertificateFactorisationprovenFactorisationchineseRemainderchineseRemainder2sqrtModP sqrtModPList sqrtModP' tonelliShanks sqrtModPPsqrtModF sqrtModFList sqrtModPPList powModWord powModIntGaussianInteger:+realimagιquotRemGquotGremGdivModGdivGmodG conjugatenormgcdGgcdG' findPrime findPrime'.^$fNumGaussianInteger$fShowGaussianInteger$fEqGaussianIntegerUniqueFactorisationunPrime$$fUniqueFactorisationGaussianInteger$fUniqueFactorisationNatural$fUniqueFactorisationInteger$fUniqueFactorisationWord$fUniqueFactorisationInt$fEqGaussianPrime$fShowGaussianPrime Prefactored prefValue prefFactors fromValue fromFactors $fUniqueFactorisationPrefactored$fNumPrefactored$fShowPrefactoredArithmeticFunction runFunctionMoebiusMoebiusNMoebiusZMoebiusP runMoebiussieveBlockMoebius$fMonoidMoebius$fSemigroupMoebius$fVectorVectorMoebius$fMVectorMVectorMoebius$fUnboxMoebius $fEqMoebius $fOrdMoebius $fShowMoebiusmultiplicativedivisors divisorsA divisorsList divisorsListA divisorsSmalldivisorsSmallAtautauAsigmasigmaAtotienttotientAjordanjordanAmoebiusmoebiusA liouville liouvilleA carmichael carmichaelAadditive smallOmega smallOmegaAbigOmega bigOmegaA expMangoldt expMangoldtA CyclicGroupCG2CG4CGOddPrimePowerCGDoubleOddPrimePowercyclicGroupFromModulocyclicGroupToModuloisPrimitiveRoot'isPrimitiveRoot$fShowCyclicGroupSieveBlockConfigsbcEmptysbcFunctionOnPrimePower sbcAppendmultiplicativeSieveBlockConfigadditiveSieveBlockConfigrunFunctionOverBlock sieveBlockmertens zetasEvenzetasghc-prim GHC.TypesNat+*^<=?-CmpNatsameNat someNatValnatVal'natValSomeNat<=GHC.BaseNothingGHC.NumNumGHC.Real FractionalPrimeNat unPrimeNatPrmunPrm array-0.5.2.0Data.Array.Base castSTUArray unsafeThaw unsafeFreezeunsafeAtboundsUArray unsafeWrite unsafeReadunsafeNewArray_idxPrtoPrimtoIdxrhodeltabyteidxmunuGHC.EnummaxBoundmap fromIntegerGHC.List takeWhile fromIntegralIntWord integer-gmpGHC.Integer.TypeIntegerHippEHDelDJustappCuRtshiftToOddCount shiftOCWord shiftOCIntshiftOCIntegerbigNatZeroCountBigNat shiftToOdd shiftOInt shiftOWord shiftOInteger shiftToOdd#shiftToOddCount# bitCountWord#GHC.PrimWord# bitCountWord bitCountInt trailZeros# splitOff#splitOffuncheckedShiftRsieveToPS sieveBytes sieveBits sieveRange sieveWords countFromTo nthPrimeCt countToNthcountAllisValid unSmoothBasistrialDivisionWithtrialDivisionPrimeWithabsmod lucasTestInt#gcdminBound!random-1.1-LLUGZ7T9DqQ5vN0Jbcd0We System.RandomStdGenrandomRbigStepenumAndMultiplyFromThenTo testParms findParmsFactors _primeFactors_compositeFactors primProof compProofFalsetrivial maybeTrivialisTrivialPrime trivialPrimes smallCert certifyBPSWfindDecomposition findFactorfindLoop bpswMessagefoundfermat TrialDivision PocklingtonTrivialfactorisedPartcofactor knownFactorstdLimit StrongFermatLucasSelfridge firstFactor secondFactorwitnessGHC.WordWord16fsBound fsPrimeTesttotientFromCanonical ppTotientcarmichaelFromCanonicalCSTSFStest primeCheckcertiFactorisationmergemergeAllinvalid wordToInt wordToInteger intToWord intToIntegernaturalToIntegerintegerToNatural integerToWordquotremdiv GaussianPrime_unGaussianPrime Data.MonoidProductSum getProductgetSum$fNumArithmeticFunctionD:R:VectorMoebius0 V_MoebiusD:R:MVectorsMoebius0 MV_Moebius IntSetProductgetIntSetProduct ListProductgetListProduct SetProduct getSetProductXor_getXorLCMgetLCMMangoldt MangoldtZero MangoldtOne MangoldtManysumMultMoebiuspointsUnderHyperbola0stepBackpointsUnderHyperbola BresenhambresXbresBeta _bresGamma _bresDelta1 _bresEpsilonDouble