!!      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t uvwxyz{|}~      !"#$%&'()*+,-./0123456789:;<=> ? @!A!B!C!D!E!F!G!H!I!J!K!L!M!NOPQRSTUVWXYZ[\]^_`abcdefghijkl"m"n"o"p"q"r"s"t"u"v"w"x"y"z"{"|"}"~"#$$$$$$$$$$%&&&&'''(((B)Safe"(c) 2018 Alexandre Rodrigues BaldMIT4Alexandre Rodrigues Bald <alexandrer_b@outlook.com> ProvisionalNon-portable (GHC extensions)None;=DKV+}arithmoiWrapper around , which has an  Eucledian instance.arithmoi@A class to represent a Euclidean domain, which is basically an  without .arithmoi4When restriced to a subring of the Euclidean domain a isomorphic to Integer, this function should match quotRem for Integers.arithmoi4When restriced to a subring of the Euclidean domain a isomorphic to Integer, this function should match divMod for Integers. arithmoi  x y* is the greatest number that divides both x and y. arithmoi  x y" is the smallest number that both x and y divide. arithmoi&Test whether two numbers are coprime .arithmoidCalculate 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).      (c) 2017-2018 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com>NoneV=arithmoi>A list of pairwise coprime numbers with their multiplicities.arithmoiUnwrap.arithmoi2Wrap a non-zero number with its multiplicity into .singleton 210 1!Coprimes {unCoprimes = [(210,1)]}arithmoi/Add a non-zero number with its multiplicity to .insert 360 1 (singleton 210 1)1Coprimes {unCoprimes = [(7,1),(5,2),(3,3),(2,4)]}4insert 2 4 (insert 7 1 (insert 5 2 (singleton 4 3))),Coprimes {unCoprimes = [(7,1),(5,2),(2,10)]}arithmoiThe 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)]-Coprimes {unCoprimes = [(28,1),(33,1),(5,2)]}&splitIntoCoprimes [(360, 1), (210, 1)]1Coprimes {unCoprimes = [(7,1),(5,2),(3,3),(2,4)]}(c) 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None &'-0FKQV]o$arithmoiThis 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"'arithmoirThis type represents elements of the multiplicative group mod m, i.e. those elements which are coprime to m. Use  toMultElement to construct.)arithmoiWrapper 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.:set -XDataKinds(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.*arithmoi.Linking type and value levels: extract modulo m as a value.+arithmoi.Linking type and value levels: extract modulo m as a value.,arithmoiHThe canonical representative of the residue class, always between 0 and m-1 inclusively.-arithmoiHThe canonical representative of the residue class, always between 0 and m-1 inclusively..arithmoiHComputes the modular inverse, if the residue is coprime with the modulo.:set -XDataKindsinvertMod (3 :: Mod 10)3Just (7 `modulo` 10) -- because 3 * 7 = 1 :: Mod 10invertMod (4 :: Mod 10)Nothing/arithmoiDrop-in replacement for , with much better performance.:set -XDataKindspowMod (3 :: Mod 10) 4> (1 `modulo` 10)0arithmoiInfix synonym of /.1arithmoi4Attempt to construct a multiplicative group element.2arithmoitFor elements of the multiplicative group, we can safely perform the inverse without needing to worry about failure.3arithmoiCreate modular value by representative of residue class and modulo. One can use the result either directly (via functions from  and 5), or deconstruct it by pattern matching. Note that 3 never returns &.4arithmoi)Computes the inverse value, if it exists.invertSomeMod (3 `modulo` 10)3Just (7 `modulo` 10) -- because 3 * 7 = 1 :: Mod 10invertMod (4 `modulo` 10)Nothing$invertSomeMod (fromRational (2 % 5)) Just 5 % 25arithmoiDrop-in replacement for `, with much better performance. When -O is enabled, there is a rewrite rule, which specialises  to 5.powSomeMod (3 `modulo` 10) 4(1 `modulo` 10)6arithmoiuBeware that division by residue, which is not coprime with the modulo, will result in runtime error. Consider using . instead.=arithmoiuBeware that division by residue, which is not coprime with the modulo, will result in runtime error. Consider using 4 instead.$%&'()*+,-./012345),-*+./0'(12$%&3450837*(c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None<Dq+(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalportableSafe{$GarithmoiFollowing property holds: LapproxPrimeCount n >= primeCount n || n >= approxPrimeCountOverestimateLimitHarithmoiH nD gives an approximation of the number of primes not exceeding n'. The approximation is fairly good for n large enough.IarithmoiFollowing property holds: GnthPrimeApprox n <= nthPrime n || n >= nthPrimeApproxUnderestimateLimitJarithmoiJ nV gives an approximation to the n-th prime. The approximation is fairly good for n large enough.GHIJ,(c) 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)Safe6FTKarithmoi6Type of primes of a given unique factorisation domain.abs (unPrime n) == unPrime n must hold for all n of type Prime tK(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)SafeLarithmoi(Infinite zero-based table of factorials.take 5 factorial [1,1,2,6,24] The time-and-space behaviour of L is similar to described in .Math.NumberTheory.Recurrencies.Bilinear#memory.MarithmoiM 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.NarithmoiN 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.OarithmoiO k computes the k%-th Lucas number. Very similar to M.ParithmoiP k computes the pair (L(k), L(k+1)) of the k7-th Lucas number and its successor. Very similar to N.QarithmoiQ 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.LMNOPQLMNOPQ(c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)SafeV RarithmoiUInfinite zero-based table of binomial coefficients (also known as Pascal triangle): (binomial !! n !! k == n! / k! / (n - k)!.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.SarithmoiInfinite zero-based table of  @https://en.wikipedia.org/wiki/Stirling_numbers_of_the_first_kind"Stirling numbers of the first kind.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.TarithmoiInfinite zero-based table of  Ahttps://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind#Stirling numbers of the second kind.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 -0 to compute stand-alone values.UarithmoiInfinite one-based table of  (https://en.wikipedia.org/wiki/Lah_number Lah numbers.  lah !! n !! k equals to lah(n + 1, k + 1).take 5 (map (take 5) lah)3[[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.VarithmoiInfinite zero-based table of  -https://en.wikipedia.org/wiki/Eulerian_number"Eulerian numbers of the first kind.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.WarithmoiInfinite zero-based table of  Qhttps://en.wikipedia.org/wiki/Eulerian_number#Eulerian_numbers_of_the_second_kind#Eulerian numbers of the second kind.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.Xarithmoi 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 T.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 -1 to compute stand-alone values.arithmoiInfinite zero-based list of  *https://en.wikipedia.org/wiki/Euler_number Euler numbers'. The algorithm used was derived from  9http://www.emis.ams.org/journals/JIS/VOL4/CHEN/AlgBE2.pdf2Algorithms for Bernoulli numbers and Euler numbersI by Kwang-Wu Chen, second formula of the Corollary in page 7. Sequence  https://oeis.org/A122045A122045 in OEIS.take 10 euler' :: [Rational]G[1 % 1,0 % 1,(-1) % 1,0 % 1,5 % 1,0 % 1,(-61) % 1,0 % 1,1385 % 1,0 % 1]YarithmoiThe same sequence as euler', but with type [a] instead of  [Ratio a] as the denominators in euler' are always 1.take 10 euler :: [Integer]$[1, 0, -1, 0, 5, 0, -61, 0, 1385, 0]Zarithmoi Infinite zero-based list of the n)-th order Euler polynomials evaluated at 1'. The algorithm used was derived from  9http://www.emis.ams.org/journals/JIS/VOL4/CHEN/AlgBE2.pdf2Algorithms for Bernoulli numbers and Euler numbersh by Kwang-Wu Chen, third formula of the Corollary in page 7. Element-by-element division of sequences  https://oeis.org/A198631A1986631 and  https://oeis.org/A006519A006519 in OEIS."take 10 eulerPolyAt1 :: [Rational]E[1 % 1,1 % 2,0 % 1,(-1) % 4,0 % 1,1 % 2,0 % 1,(-17) % 8,0 % 1,31 % 2]arithmoiHelper for common code in =bernoulli, euler, eulerPolyAt1. All three sequences rely on  stirling2 and have the same general structure of zipping four lists together with multiplication, with one of those lists being the sublists in  stirling24, and two of them being the factorial sequence and  cycle [1, -1]#. The remaining list is passed to  helperForB_E_EP@ as an argument.Note: This function has a ([Ratio a] -> [Ratio a]) argument because bernoulli !! n will use, for all nonnegative n, every element in stirling2 !! n, while euler, eulerPolyAt1 only use tail $ stirling2 !! n(. As such, this argument serves to pass id in the former case, and tail in the latter. RSTUVWXYZ RSTUVWXYZ2"(c) 2018 Alexandre Rodrigues BaldMIT4Alexandre Rodrigues Bald <alexandrer_b@outlook.com> ProvisionalNon-portable (GHC extensions)SafeQVparithmoi:Infinite list of generalized pentagonal numbers. Example: take 10 pents#[0, 1, 2, 5, 7, 12 ,15, 22, 26, 35]arithmoiWhen calculating the n-th partition number p(n) using the sum 8p(n) = p(n-1) + p(n-2) - p(n-5) - p(n-7) + p(n-11) + ...U, the signs of each term alternate every two terms, starting with a positive sign. pentagonalSignsN takes a list of numbers and produces such an alternated sequence. Examples:pentagonalSigns [1..5][1, 2, -3, -4, 5]pentagonalSigns [1..6][1, 2, -3, -4, 5, 6][arithmoiInfinite zero-based table of  https://oeis.org/A000041partition numbers.take 10 partition"[1, 1, 2, 3, 5, 7, 11, 15, 22, 30]:set -XDataKindspartition !! 1000 :: Mod 1000(991 `modulo` 1000)["(c) 2018 Alexandre Rodrigues BaldMIT4Alexandre Rodrigues Bald <alexandrer_b@outlook.com> ProvisionalNon-portable (GHC extensions)SafeLMNOPQRSTUVWXYZ[[3(c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNone 4(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<D1 \arithmoi: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.]arithmoi: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.^arithmoiCalculate 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._arithmoiCalculate 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.`arithmoiReturns % 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 c.aarithmoiXTest whether the argument is a square. After a number is found to be positive, first c@ is checked, if it is, the integer square root is calculated.barithmoi.Test whether the input (a nonnegative number) n is a square. The same as aW, 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.carithmoiTest whether a non-negative number may be a square. Non-negativity is not checked, passing negative arguments may cause any kind of havoc.First the remainder modulo 256 is checked (that can be calculated easily without division and eliminates about 82% of all numbers). After that, the remainders modulo 9, 25, 7, 11 and 13 are tested to eliminate altogether about 99.436% of all numbers.This is the test used by `@. For large numbers, the slower but more discriminating test isPossibleSqure2 is faster.darithmoiTest 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 c, 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). \]^_`abcd \]^_`abcd (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None<D@earithmoi[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.farithmoi[Calculate the integer fourth root of a nonnegative number, that is, the largest integer r with r^4 <= n. The condition is not checked.garithmoiReturns Nothing if n is not a fourth power, Just r if n == r^4 and r >= 0.harithmoisTest whether an integer is a fourth power. First nonnegativity is checked, then the unchecked test is called.iarithmoiITest whether a nonnegative number is a fourth power. The condition is not$ checked. If a number passes the j0 test, its integer fourth root is calculated.jarithmoiRTest whether a nonnegative number is a possible fourth power. The condition is not6 checked. This eliminates about 99.958% of numbers.efghijefghij (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None<DTkarithmoi.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.larithmoi9Calculate 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.marithmoiReturns Nothing# if the argument is not a cube, Just r if n == r^3.narithmoi"Test whether an integer is a cube.oarithmoi8Test whether a nonnegative integer is a cube. Before k 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.parithmoi}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.arithmoiHapproximate cube root, about 50 bits should be correct for large numbersklmnopklmnop (c) 2012 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None<uqarithmoi 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.rarithmoigeneralInversion 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  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.qrrq (c) 2012 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None<?sarithmoi 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.tarithmoigeneralInversion 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 . 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.stts5(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneDarithmoiRemove 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).arithmoiSpecialised version for <. Precondition: argument strictly positive (not checked).arithmoiSpecialised version for 2. Precondition: argument nonzero (not checked).arithmoiSpecialised version for 2. Precondition: argument nonzero (not checked).arithmoiSpecialised version for 2. Precondition: argument nonzero (not checked).arithmoiCount trailing zeros in a E. Precondition: argument nonzero (not checked, Integer invariant).arithmoiRemove factors of 2. If  n = 2^k*m with m odd, the result is m . Precondition: argument not 0 (not checked).arithmoiSpecialised version for 2. Precondition: argument nonzero (not checked).arithmoiSpecialised version for 2. Precondition: argument nonzero (not checked).arithmoiSpecialised version for 2. Precondition: argument nonzero (not checked).arithmoiLShift argument right until the result is odd. Precondition: argument not 0, not checked.arithmoiLike ., but count the number of places to shift too.arithmoiNumber of 1-bits in a .arithmoiNumber of 1-bits in a .arithmoiNumber of 1-bits in an .arithmoi3It is difficult to convince GHC to unbox output of  and  'splitOff.go'K, so we fallback to a specialized unboxed version to minimize allocations.arithmoieMerges two ordered lists into an ordered list. Checks for neither its precondition or postcondition.arithmoi Work around -https://ghc.haskell.org/trac/ghc/ticket/14085 (c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneDuarithmoiCalculate an integer root, u k n computes the (floor of) the k-th root of n, where k must be positive. r = u 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, u 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.varithmoiv k n returns  if n is not a k-th power,  r if n == r^k. If k is divisible by 4, 3 or 2i, a residue test is performed to avoid the expensive calculation if it can thus be determined that n is not a k -th power.warithmoiw k n checks whether n is a k -th power.xarithmoix n checks whether n == r^k for some k > 1.yarithmoiy 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.zarithmoiz 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 y0 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.uvwxyzuvwxyz4(c) 2011 Daniel Fischer, 2017-2018 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None]u{arithmoi%Represents three possible values of  +https://en.wikipedia.org/wiki/Jacobi_symbol Jacobi symbol.arithmoi +https://en.wikipedia.org/wiki/Jacobi_symbol Jacobi symboll of two arguments. The lower argument ("denominator") must be odd and positive, this condition is checked.2If arguments have a common factor, the result is }, otherwise it is | or ~.jacobi 1001 9911)Zero -- arguments have a common factor 11jacobi 1001 9907MinusOne{~}|{~}|6/(c) 2011 Daniel Fischer, 2017 Andrew LelechenkoMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneD+larithmoi 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.arithmoiMiller-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.arithmoi 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.arithmoi 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).arithmoiPrimality 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.arithmoipThe Lucas-Selfridge test, including square-check, but without the Fermat test. For package-internal use only.(c) 2011 Daniel FischerMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None4garithmoi 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.arithmoi%chineseRemainder2 (r_1,m_1) (r_2,m_2) calculates the solution of  r "a r_k (mod m_k)if m_1 and m_2 are coprime.(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneD@arithmoiGreatest common divisor of two ,s, calculated with the binary gcd algorithm.arithmoiTest whether two 9s are coprime, using an abbreviated binary gcd algorithm.arithmoiGreatest common divisor of two ,s, calculated with the binary gcd algorithm.arithmoiTest whether two 9s are coprime, using an abbreviated binary gcd algorithm.arithmoiGreatest common divisor of two ,s, calculated with the binary gcd algorithm.arithmoiTest whether two s are coprime.arithmoiGreatest common divisor of two ,s, calculated with the binary gcd algorithm.arithmoiTest whether two s are coprime.(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneD]\^arithmoiCalculate 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.arithmoidCalculate 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 78) 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).arithmoiuTest whether two numbers are coprime using an abbreviated binary gcd algorithm. A little bit faster than checking binaryGCD a b == 1B if one of the arguments is even, much faster if both are even.!The remarks about performance at K apply here too, use this function only at the types with rewrite rules.ORelies on twos complement or sign and magnitude representaion for signed types.(c) 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None &'-DFV arithmoiPoint on unknown curve.arithmoinWe 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.arithmoiExtract x-coordinate.arithmoiExtract z-coordinate.arithmoi 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 .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.arithmoiIf 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.arithmoiMultiply 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.arithmoi1Multiply by given number, using binary algorithm.arithmoiFor debugging.arithmoiIn projective space Cs are equal, if they are both at infinity or if respective ratios  /  are equal. 9(c) 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)Safe%:(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None<V]Z arithmoi!Compact store of primality flags.arithmoiSieve 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.arithmoi4Generate a list of primes for consumption from a .arithmoiAReturns true if integer is beyond representation range of type a.arithmoiQExtracts the longest strictly increasing prefix of the list (possibly infinite).arithmoiAscending list of primes.take 10 primes$[2, 3, 5, 7, 11, 13, 17, 19, 23, 29] is a polymorphic list, so the results of computations are not retained in memory. Make it monomorphic to take advantages of memoization. Compare:set +sprimes !! 1000000 :: Int15485867 (5.32 secs, 6,945,267,496 bytes)primes !! 1000000 :: Int15485867 (5.19 secs, 6,945,267,496 bytes)againstlet primes' = primes :: [Int]primes' !! 1000000 :: Int15485867 (5.29 secs, 6,945,269,856 bytes)primes' !! 1000000 :: Int15485867(0.02 secs, 336,232 bytes)arithmoi(List of primes in the form of a list of s, more compact than , thus it may be better to use  >>= @ than keeping the list of primes alive during the entire run.arithmoiSieve up to bound in one go.arithmoi n* creates the list of primes not less than n.arithmoi 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.(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None(c) 2018 Frederick SchneiderMIT7Frederick Schneider <frederick.schneider2011@gmail.com> ProvisionalNon-portable (GHC extensions)NoneVarithmoiZAn abstract representation of a smooth basis. It consists of a set of coprime numbers "e2.arithmoiBuild a " from a set of coprime numbers "e2. import qualified Data.Set as SetfromSet (Set.fromList [2, 3])Just (SmoothBasis [2, 3])2fromSet (Set.fromList [2, 4]) -- should be coprimeNothing/fromSet (Set.fromList [1, 3]) -- should be >= 2NothingarithmoiBuild 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 coprimeNothing!fromList [1, 3] -- should be >= 2NothingarithmoiBuild a ) from a list of primes below given bound.fromSmoothUpperBound 10Just (SmoothBasis [2, 3, 5, 7])fromSmoothUpperBound 1Nothingarithmoi(Generate an infinite ascending list of  +https://en.wikipedia.org/wiki/Smooth_numbersmooth numbers over a given smooth basis.import Data.Maybe1take 10 (smoothOver (fromJust (fromList [2, 5])))#[1, 2, 4, 5, 8, 10, 16, 20, 25, 32]arithmoiGenerate 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  in such cases.import Data.Maybe6smoothOverInRange (fromJust (fromList [2, 5])) 100 200[100, 125, 128, 160, 200]arithmoiGenerate 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  in such cases.MSuffix BF stands for the brute force algorithm, involving a lot of divisions.import Data.Maybe8smoothOverInRangeBF (fromJust (fromList [2, 5])) 100 200[100, 125, 128, 160, 200]arithmoioisValid assumes that the list is sorted and unique and then checks if the list is suitable to be a SmoothBasis.;(c) 2011 Daniel FischerMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None!arithmoisqrtModP 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.arithmoisqrtModPList n prime* computes the list of all square roots of n modulo prime. prime must/ be a (positive) prime. The precondition is not checked.arithmoisqrtModP' 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.arithmoitonelliShanks 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.arithmoisqrtModPP 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 primearithmoisqrtModF 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.arithmoisqrtModFList 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.arithmoisqrtModPPList n (prime,expo)/ calculates the list of all square roots of n modulo  prime^expo . The same restriction as in  applies to the arguments.<(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)Nonexarithmoi 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.arithmoi 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.arithmoiCheck whether a number is coprime to all of the numbers in the list (assuming that list contains only numbers > 1 and is ascending).arithmoi bound n tests whether n is coprime to all primes <= bound. If  n <= bound^2., this is a full prime test, but very slow if n has no small prime divisors.=(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None-FV]; arithmoi n% produces the prime factorisation of n.  0) is an error and the factorisation of 1 is empty. Uses a < produced in an arbitrary manner from the bit-pattern of n.arithmoiLike $, but without input checking, hence n > 1 is required.arithmoi 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.arithmoi 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.arithmoiLike $, but without input checking, so n must be larger than 1.arithmoiA 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.arithmoi 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.arithmoi 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.arithmoi7The 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.arithmoi^Same as map (id *** flip multiply p) [from, thn .. to], but calculated in more efficient way.arithmoi 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.arithmoiFor 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_ECMarithmoi"Lower bound for composite divisorsarithmoi Standard PRNGarithmoi3Estimated number of digits of smallest prime factorarithmoiThe number to factorisearithmoi#List of prime factors and exponentsarithmoi"Lower bound for composite divisorsarithmoiA primality testarithmoiA PRNGarithmoiInitial PRNG statearithmoi7Estimated number of digits of the smallest prime factorarithmoiThe number to factorisearithmoi#List of prime factors and exponents >(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None%arithmoi5An 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.arithmoi#A suggested Pocklington certificatearithmoi2Primality should be provable by trial division to alimitarithmoiaprime6 is said to be obviously prime, that holds for primes < 30arithmoiPrimality assumedarithmoidA proof of primality of a positive number. The type is abstract to ensure the validity of proofs.arithmoi%The number whose primality is proved.arithmoi9An 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.arithmoicompo == firstDiv*secondDiv, where all are > 1arithmoicompo" fails the strong Fermat test for  fermatBasearithmoicompo fails the Lucas-Selfridge testarithmoiNo particular reason givenarithmoihA proof of compositeness of a positive number. The type is abstract to ensure the validity of proofs.arithmoi)The number whose compositeness is proved.arithmoi<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.arithmoi@ transforms a proof of primality into an argument for primality.arithmoi 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.arithmoiKnot exported, this is the one place where invalid proofs can be constructedarithmoiK transforms a proof of compositeness into an argument for compositeness.arithmoi 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.arithmoiTnot exported, here is where invalid proofs can be constructed, they must not leakarithmoiCheck the validity of a z. Since it should be impossible to construct invalid certificates by the public interface, this should never return .arithmoiCheck the validity of a q. Since it should be impossible to create invalid proofs by the public interface, this should never return .arithmoiCheck the validity of a q. Since it should be impossible to create invalid proofs by the public interface, this should never return .arithmoi\ records a trivially known prime. If the argument is not one of them, an error is raised.arithmoi\ finds out if its argument is a trivially known prime or not and returns the appropriate.arithmoi; checks whether its argument is a trivially known prime.arithmoiList of trivially known primes.arithmoiCertify 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.arithmoi 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 divisorsarithmoiCertify 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.arithmoimFind a decomposition of p-1 for the pocklington certificate. Usually bloody slow if p-1 has two (or more) large prime divisors. arithmoiFind 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. arithmoi2Find a factor or say with which curve to continue. arithmoi@Message in the unlikely case a Baillie PSW pseudoprime is found. arithmoiFound a factor arithmoiFermat failure3?(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)Nonearithmoi 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(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)NoneF arithmoi n( produces the prime factorisation of nF, proving the primality of the factors, but doesn't report the proofs.arithmoi n produces a  with a default bound of 100000.arithmoi 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).arithmoi4verify that we indeed have a correct primality proofarithmoiproduce 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.arithmoiproduce 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.arithmoiVmerge two lists of factors, so that the result is strictly increasing (wrt the primes)arithmoi[merge a list of lists of factors so that the result is strictly increasing (wrt the primes) arithmoi2message for an invalid proof, should never be usedarithmoi"Lower bound for composite divisorsarithmoiA primality testarithmoiA PRNGarithmoiInitial PRNG statearithmoi7Estimated number of digits of the smallest prime factorarithmoiThe number to factorisearithmoi5List of prime factors, exponents and primality proofs(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)Nonee @(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> Provisional non-portableNone<VarithmoiMaximal allowed argument of . Currently 8e18.arithmoi 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 . Requires O(n^0.5)' space, the time complexity is roughly O(n^0.7). For small bounds,  n( simply counts the primes not exceeding n, for bounds from 30000T on, Meissel's algorithm is used in the improved form due to D.H. Lehmer, cf.  \http://en.wikipedia.org/wiki/Prime_counting_function#Algorithms_for_evaluating_.CF.80.28x.29.arithmoiMaximal allowed argument of . Currently 1.5e17.arithmoi n calculates the n%-th prime. Numbering of primes is 1 -based, so  1 == 2. Requires O((n*log n)^0.5)' space, the time complexity is roughly O((n*log n)^0.7A. The argument must be strictly positive, and must not exceed .(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> Provisional non-portableNone|GHIJHGJIA(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None GHIJ(c) 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)NoneD3arithmoipowMod 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. powMod 2 3 53"powMod 3 12345678901234567890 10011 See also B and C.For finite numeric types (, , 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 -- correctpowMod 3 101 (2^60-1 :: Int64)01115647832265427613 -- incorrect due to overflowpowModInt 3 101 (2^60-1 :: Int)1018105167100379328 -- correctarithmoiSpecialised version of (, able to handle large moduli correctly.powModWord 3 101 (2^60-1)1018105167100379328arithmoiSpecialised version of (, able to handle large moduli correctly. > powModInt 3 101 (2^60-1)1018105167100379328D(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)NoneR\`aeghkmnuvwxy\a`knmehguwvxy(c) 2011 Daniel FischerMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None%arithmoiList all modular square roots.:set -XDataKindssqrtsMod (1 :: Mod 60)> [(1 `modulo` 60),(49 `modulo` 60),(41 `modulo` 60),(29 `modulo` 60),(31 `modulo` 60),(19 `modulo` 60),(11 `modulo` 60),(59 `modulo` 60)]arithmoiZList all square roots modulo a number, which factorisation is passed as a second argument.&sqrtsModFactorisation 1 (factorise 60)[1,49,41,29,31,19,11,59]arithmoi.List all square roots modulo power of a prime.-sqrtsModPrimePower 7 (fromJust (isPrime 3)) 2[4,5]-sqrtsModPrimePower 9 (fromJust (isPrime 3)) 3[3,12,21,24,6,15]arithmoi&List all square roots by prime modulo.&sqrtsModPrime 1 (fromJust (isPrime 5))[1,4]&sqrtsModPrime 0 (fromJust (isPrime 5))[0]&sqrtsModPrime 2 (fromJust (isPrime 5))[]!arithmoisqrtModP' 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."arithmoip must be of form 4k + 1#arithmoitonelliShanks 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 prime(, using the Tonelli-Shanks algorithm.$arithmoi/prime must be odd, n must be coprime with prime '(c) 2016 Chris Fredrickson, Google Inc.MIT1Chris Fredrickson <chris.p.fredrickson@gmail.com> ProvisionalNon-portable (GHC extensions)None6b arithmoi<A Gaussian integer is a+bi, where a and b are both integers.arithmoiThe imaginary unit, where   .^ 2 == -1arithmoiConjugate a Gaussian integer.arithmoi2The square of the magnitude of a Gaussian integer.arithmoi2Compute whether a given Gaussian integer is prime.arithmoiAn infinite list of the Gaussian primes. Uses primes in Z to exhaustively generate all Gaussian primes (up to associates), in order of ascending magnitude.arithmoiRCompute the GCD of two Gaussian integers. Result is always in the first quadrant.arithmoiTFind a Gaussian integer whose norm is the given prime number of form 4k + 1 using  dhttp://www.ams.org/journals/mcom/1972-26-120/S0025-5718-1972-0314745-6/S0025-5718-1972-0314745-6.pdfHermite-Serret algorithm.arithmoi*Raise a Gaussian integer to a given power. arithmoiTCompute the prime factorisation of a Gaussian integer. This is unique up to units (+- 1, +3- i). Unit factors are not included in the result.%arithmoiHRemove all (1:+1) factors from the argument, avoiding complex division.&arithmoiJRemove p and conj p factors from the argument, avoiding complex division.&arithmoiGaussian prime parithmoi%Precomputed norm of p, of form 4k + 1arithmoiHExpected number of factors (either p or conj p) in Gaussian integer zarithmoiGaussian integer z  68E'(c) 2016 Chris Fredrickson, Google Inc.MIT1Chris Fredrickson <chris.p.fredrickson@gmail.com> ProvisionalNon-portable (GHC extensions)NoneG "(c) 2018 Alexandre Rodrigues BaldMIT4Alexandre Rodrigues Bald <alexandrer_b@outlook.com> ProvisionalNon-portable (GHC extensions)None6QV^parithmoiAAn Eisenstein integer is a + b, where a and b are both integers.arithmoi1The imaginary unit for Eisenstein integers, where , == (-1/2) + ((sqrt 3)/2) == exp(2*pi*/3)0and  is the usual imaginary unit with  == -1.'arithmoi Returns an EisensteinInteger1's sign, and its associate in the first sextant.arithmoiSList of all Eisenstein units, counterclockwise across all sextants, starting with 1.arithmoiProduce a list of an EisensteinInteger's associates.(arithmoi4Takes an Eisenstein prime whose norm is of the form 3k + 1 with ki a nonnegative integer, and return its primary associate. * Does *not* check for this precondition. * head2 will fail when supplied a number unsatisfying it.)arithmoi3Function that does most of the underlying work for divMod and quotRemu, apart from choosing the specific integer division algorithm. This is instead done by the calling function (either divMod which uses div, or quotRem , which uses quot.)arithmoiConjugate a Eisenstein integer.arithmoi4The square of the magnitude of a Eisenstein integer.arithmoiChecks if a given EisensteinInteger is prime. EisensteinInteger&s whose norm is a prime congruent to 0 or 1 modulo 3 are prime. See  "http://thekeep.eiu.edu/theses/2467BBandara, Sarada, "An Exposition of the Eisenstein Integers" (2016) , page 12.arithmoiRemove 1 -  factors from an EisensteinIntegerI, and calculate that prime's multiplicity in the number's factorisation.arithmoiMFind an Eisenstein integer whose norm is the given prime number in the form 3k + 1 using a modification of the  dhttp://www.ams.org/journals/mcom/1972-26-120/S0025-5718-1972-0314745-6/S0025-5718-1972-0314745-6.pdfHermite-Serret algorithm.The maintainer  Dhttps://github.com/cartazio/arithmoi/pull/121#issuecomment-415010647Andrew Lelechenko/ derived the following: * Each prime of form 3n+1 is actually of form 6k+1 . * One has R(z+3k)^2 "a z^2 + 6kz + 9k^2 "a z^2 + (6k+1)z - z + 9k^2 "a z^2 - z + 9k^2 (mod 6k+1).The goal is to solve z^2 - z + 1 "a 0 (mod 6k+1) . One has: $z^2 - z + 9k^2 "a 9k^2 - 1 (mod 6k+1) (z+3k)^2 "a 9k^2-1 (mod 6k+1) z+3k = sqrtMod(9k^2-1) z = sqrtMod(9k^2-1) - 3kFor example, let p = 7, then k = 1. Square root of 9*1^2-1 modulo 7 is 1.And z = 1 - 3*1 = -2 "a 5 (mod 7).Truly, +norm (5 :+ 1) = 25 - 5 + 1 = 21 "a 0 (mod 7).arithmoi%An infinite list of Eisenstein primes. Uses primes in Z to exhaustively generate all Eisenstein primes in order of ascending magnitude. * Every prime is in the first sextant, so the list contains no associates. * Eisenstein primes from the whole complex plane can be generated by applying  associates to each prime in this list.arithmoiWCompute the prime factorisation of a Eisenstein integer. This is unique up to units (+- 1, +d- , +/- ). * Unit factors are not included in the result. * All prime factors are primary i.e. e "a 2 (modE 3)", for an Eisenstein prime factor e.This function works by factorising the norm of an Eisenstein integer and then, for each prime factor, finding the Eisenstein prime whose norm is said prime factor with  findPrime.sThis is only possible because the norm function of the Euclidean Domain of Eisenstein integers is multiplicative: #norm (e1 * e2) == norm e1 * norm e2 for any two EisensteinIntegers e1, e2.!In the previously mentioned work  "http://thekeep.eiu.edu/theses/2467BBandara, Sarada, "An Exposition of the Eisenstein Integers" (2016)R, in Theorem 8.4 in Chapter 8, a way is given to express any Eisenstein integer  as :(-1)^a * ^b * (1 - )^c * product [_i^a_i | i <- [1..N]] where  a, b, c, a_i are nonnegative integers, N > 1 is an integer and _i4 are primary primes (for a primary Eisenstein prime p, p "a 2 (modE 3), see primary above).Aplying norm# to both sides of Theorem 8.4: Knorm  = norm ((-1)^a * ^b * (1 - )^c * product [ _i^a_i | i <- [1..N]]) == `norm  = norm ((-1)^a) * norm (^b) * norm ((1 - )^c) * norm (product [ _i^a_i | i <- [1..N]]) == `norm  = (norm (-1))^a * (norm )^b * (norm (1 - ))^c * product [ norm (_i^a_i) | i <- [1..N]] == anorm  = (norm (-1))^a * (norm )^b * (norm (1 - ))^c * product [ (norm _i)^a_i) | i <- [1..N]] == Cnorm  = 1^a * 1^b * 3^c * product [ (norm _i)^a_i) | i <- [1..N]] == 7norm  = 3^c * product [ (norm _i)^a_i) | i <- [1..N]] where  a, b, c, a_i are nonnegative integers, and N > 1 is an integer.\The remainder of the Eisenstein integer factorisation problem is about finding appropriate [e_i | i <- [1..M] such that ;(nub . map norm) [e_i | i <- [1..N]] == [_i | i <- [1..N]] where  1 < N <= M are integers, nub removes duplicates and == is equality on sets. The reason M >= N is because the prime factors of an Eisenstein integer may include a prime factor and its conjugate, meaning the number may have more Eisenstein prime factors than its norm has integer prime factors.*arithmoiRemove p and  conjugate p# factors from the argument, where p is an Eisenstein prime.+arithmoi0Divide an Eisenstein integer by an even integer.*arithmoiEisenstein prime parithmoi Conjugate of parithmoiPrecomputed norm of p , of form 4k + 1arithmoi#Expected number of factors (either p or  conjugate p) in Eisenstein integer zarithmoiEisenstein integer z6(c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None7FTe %arithmoi&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.K%&'(K%&'((c) 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)NoneFTZ3arithmoiA 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: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: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)-Coprimes {unCoprimes = fromList [(2,4),(3,3),G (41666666666666666666666666669,1),(111111111111111111111111111115,1),K (1000000000000000000000000000057,1),(2000000000000000000000000000071,2)]}+prefFactors $ totient $ totient (p^2 * q^3)UCoprimes {unCoprimes = fromList [(2,22),(3,8),(5,3),(39521,1),(199937,1),(6046667,1),V (227098769,1),(361696272343,1),(85331809838489,1),(22222222222222222222222222223,1),I (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)))4arithmoiNumber itself.5arithmoicList of pairwise coprime (but not neccesarily prime) factors, accompanied by their multiplicities.6arithmoiCreate 3 from a given number. fromValue 123WPrefactored {prefValue = 123, prefFactors = Coprimes {unCoprimes = fromList [(123,1)]}}7arithmoiCreate 3` from a given list of pairwise coprime (but not neccesarily prime) factors with multiplicities.4fromFactors (splitIntoCoprimes [(140, 1), (165, 1)])ePrefactored {prefValue = 23100, prefFactors = Coprimes {unCoprimes = fromList [(5,2),(28,1),(33,1)]}}4fromFactors (splitIntoCoprimes [(140, 2), (165, 3)])kPrefactored {prefValue = 88045650000, prefFactors = Coprimes {unCoprimes = fromList [(5,5),(28,2),(33,3)]}}3456734567F(c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None&';arithmoiA 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 Product or SumE), and the second argument is convenient for unwrapping (typically,  getProduct or getSum).=arithmoi1Convert to function. The value on 0 is undefined.,arithmoiFactorisation 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%V\>arithmoi)Find all solutions of ax + b "a 0 (mod m).:set -XDataKinds:solveLinear (6 :: Mod 10) 4 -- solving 6x + 4 "a 0 (mod 10)![(1 `modulo` 10),(6 `modulo` 10)]?arithmoi/Find all solutions of ax + bx + c "a 0 (mod m).:set -XDataKindsDsolveQuadratic (1 :: Mod 32) 0 (-17) -- solving x - 17 "a 0 (mod 32)C[(9 `modulo` 32),(25 `modulo` 32),(7 `modulo` 32),(23 `modulo` 32)]>arithmoiaarithmoibarithmoi list of x?arithmoiaarithmoibarithmoicarithmoi list of c>?>?!(c) 2018 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None >?DFT@arithmoi$Represents three possible values of  -https://en.wikipedia.org/wiki/Mbius_functionMbius function.Aarithmoi"1Barithmoi0Carithmoi1DarithmoiConvert to any numeric type.Earithmoi5Evaluate 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 $G.sieveBlockMoebius 1 10d[MoebiusP, MoebiusN, MoebiusN, MoebiusZ, MoebiusN, MoebiusP, MoebiusN, MoebiusZ, MoebiusZ, MoebiusP]@ABCDE@ABCDEH(c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None%FTVtNarithmoiYCreate a multiplicative function from the function on prime's powers. See examples below.Parithmoi2The set of all (positive) divisors of an argument.RarithmoiVThe unsorted list of all (positive) divisors of an argument, produced in lazy fashion.TarithmoiSame as O:, but with better performance on cost of type restriction.Varithmoi1The number of (positive) divisors of an argument. %tauA = multiplicative (\_ k -> k + 1)XarithmoiThe sum of the k1-th powers of (positive) divisors of an argument. HsigmaA = multiplicative (\p k -> sum $ map (p ^) [0..k]) sigmaA 0 = tauAZarithmoi,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).\arithmoi3Calculates the k-th Jordan function of an argument. jordanA 1 = totientA^arithmoiCalculates the  4https://en.wikipedia.org/wiki/Ramanujan_tau_functionRamanujan tau function of a positive number n, using formulas given (http://www.numbertheory.org/php/tau.htmlhere`arithmoi.Calculates the Mbius function of an argument.barithmoi1Calculates the Liouville function of an argument.darithmoixCalculates the Carmichael function for a positive integer, that is, the (smallest) exponent of the group of units in !$/(n).earithmoiTCreate an additive function from the function on prime's powers. See examples below.garithmoi!Number of distinct prime factors. "smallOmegaA = additive (\_ _ -> 1)iarithmoi3Number of prime factors, counted with multiplicity.  bigOmegaA = additive (\_ k -> k)karithmoi+The exponent of von Mangoldt function. Use log expMangoldtA) to recover von Mangoldt function itself.#@ABCDNOPQRSTUVWXYZ[\]^_`abcdefghijk(c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None &;<=@ABCDNOPQRSTUVWXYZ[\]^_`abcdefghijk&;<=NOPQRSTUVWXYZ[\]^_`@ABCDabefghicdjk"(c) 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None06<N] larithmoiL'PrimitiveRoot m' is a type which is only inhabited by primitive roots of n.marithmoiExtract primitive root value.narithmoiGet cyclic group structure.oarithmoiSA 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.parithmoiResidues modulo 2.qarithmoiResidues modulo 4.rarithmoiResidues modulo p^k for odd prime p.sarithmoiResidues modulo 2p^k for odd prime p.tarithmoiwCheck whether a multiplicative group of residues, characterized by its modulo, is cyclic and, if yes, return its form.cyclicGroupFromModulo 4Just CG4"cyclicGroupFromModulo (2 * 13 ^ 3),Just (CGDoubleOddPrimePower (PrimeNat 13) 3)cyclicGroupFromModulo (4 * 13)NothinguarithmoiUExtract modulo and its factorisation from a cyclic multiplicative group of residues.cyclicGroupToModulo CG4SPrefactored {prefValue = 4, prefFactors = Coprimes {unCoprimes = fromList [(2,2)]}}:set -XTypeFamilies;cyclicGroupToModulo (CGDoubleOddPrimePower (PrimeNat 13) 3)]Prefactored {prefValue = 4394, prefFactors = Coprimes {unCoprimes = fromList [(2,1),(13,3)]}}varithmoiv 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.&let Just cg = cyclicGroupFromModulo 13isPrimitiveRoot' cg 1FalseisPrimitiveRoot' cg 2Truewarithmoi,Check whether a given modular residue is a  5https://en.wikipedia.org/wiki/Primitive_root_modulo_nprimitive root.:set -XDataKindsisPrimitiveRoot (1 :: Mod 13)FalseisPrimitiveRoot (2 :: Mod 13)True(Here is how to list all primitive roots:;mapMaybe isPrimitiveRoot [minBound .. maxBound] :: [Mod 13]E[(2 `modulo` 13), (6 `modulo` 13), (7 `modulo` 13), (11 `modulo` 13)]-This function is a convenient wrapper around vH. The latter provides better control and performance, if you need them.xarithmoi+Calculate the size of a given cyclic group. lnmopqrstuvwx opqrstuxlmnwv#(c) 2018 Bhavik MehtaMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> Provisional Non-portableNone%VarithmoiComputes the discrete logarithm. Currently uses a combination of the baby-step giant-step method and Pollard's rho algorithm, with Bach reduction.-arithmoi8group structure (must be the multiplicative group mod m)arithmoiaarithmoibarithmoiresultI(c) 2011 Daniel FischerMIT1Daniel Fischer <daniel.is.fischer@googlemail.com> ProvisionalNon-portable (GHC extensions)None5$%&'()*+,-./012345{~}|lmnopqrstuvwxJ(c) 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)NoneDVParithmoi>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 = (*) }arithmoivalue of a function on 1arithmoi*how to evaluate a function on prime powersarithmoi8how to combine values of a function on coprime argumentsarithmoiRCreate a config for a multiplicative function from its definition on prime powers.arithmoiMCreate a config for an additive function from its definition on prime powers.arithmoiTEvaluate 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:?sieveBlockUnboxed (SieveBlockConfig 1 (\_ a -> a + 1) (*)) 1 10[1,2,2,3,2,4,2,4,3,4]$(c) 2017 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)NoneDV4Zarithmoi 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 , read more details there.%runFunctionOverBlock carmichaelA 1 10[1,1,2,2,4,2,6,2,6,4]arithmoiTEvaluate 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+)). is similar to  up to flavour of KLa, but is typically 7x-10x slower and consumes 3x memory. Use unboxed version whenever possible.9For example, following code lists smallest prime factors:;sieveBlock (SieveBlockConfig maxBound (\p _ -> p) min) 2 10[2,3,2,5,2,7,2,3,2,11]4And this is how to factorise all numbers in a block:<sieveBlock (SieveBlockConfig [] (\p k -> [(p,k)]) (++)) 2 10^[[(2,1)],[(3,1)],[(2,2)],[(5,1)],[(2,1),(3,1)],[(7,1)],[(2,3)],[(3,2)],[(2,1),(5,1)],[(11,1)]] E E%(c) 2018 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None]=karithmoiKCompute individual values of Mertens function in O(n^(2/3)) time and space.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..arithmoi0Compute sum (map (x -> runMoebius (mu x) * f x))M(c) 2018 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)None]J0/arithmoi$Straightforward computation of [ n 0x x | x <- [hi, hi - 1 .. lo] ]. Unfortunately, such list generator performs poor, so we fall back to manual recursion.1arithmoi0bresenham(x+1) -> bresenham(x) for x >= (2n)^1/32arithmoi"Division-free computation of [ n 0v 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 .2N"(c) 2018 Alexandre Rodrigues BaldMIT4Alexandre Rodrigues Bald <alexandrer_b@outlook.com> ProvisionalNon-portable (GHC extensions)SafeWarithmoihJoins two lists element-by-element together into one, starting with the first one provided as argument.(take 10 $ intertwine [0, 2 ..] [1, 3 ..][0, 1, 2, 3, 4, 5, 6, 7, 8, 9]arithmoiUSkips every odd-indexed element from an infinite list. Do NOT use with finite lists.take 10 (skipOdds [0, 1 ..])#[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]arithmoiVSkips every even-indexed element from an infinite list. Do NOT use with finite lists.take 10 (skipEvens [0, 1 ..])#[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]arithmoiSums every element of an infinite list up to a certain precision. I.e. once an element falls below the given threshold it stops traversing the list.suminf 1e-14 (iterate (/ 10) 1)1.1111111111111112'(c) 2016 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)SafeVjMarithmoi\Infinite sequence of exact values of Riemann zeta-function at even arguments, starting with (0)3. Note that due to numerical errors conversion to 3 may return values below 1:,approximateValue (zetasEven !! 25) :: Double0.9999999999999996DUse your favorite type for long-precision arithmetic. For instance, OP works fine:import Data.Number.Fixed2approximateValue (zetasEven !! 25) :: Fixed Prec5041.00000000000000088817842111574532859293035196051773arithmoi~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). take 5 (zetas 1e-14) :: [Double]J> [-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, OP).("(c) 2018 Alexandre Rodrigues BaldMIT4Alexandre Rodrigues Bald <alexandrer_b@outlook.com> ProvisionalNon-portable (GHC extensions)SafeV|arithmoi]Infinite sequence of exact values of Dirichlet beta-function at odd arguments, starting with (1). @> approximateValue (betasOdd !! 25) :: Double 0.9999999999999987Using OP: i> approximateValue (betasOdd !! 25) :: Fixed Prec50 0.99999999999999999999999960726927497384196726751694z4arithmoibetasOdd , but with forall a . Floating a => a instead of ExactPi s. Used in  betasEven.arithmoi9Infinite sequence of approximate values of the Dirichlet = function at positive even integer arguments, starting with (0).arithmoiInfinite sequence of approximate (up to given precision) values of Dirichlet beta-function at integer arguments, starting with (0)!. The algorithm used to compute & for even arguments was derived from  #https://arxiv.org/pdf/0910.5004.pdfVAn Euler-type formula for (2n) and closed-form expressions for a class of zeta series! by F. M. S. Lima, formula (12). s> take 5 (betas 1e-14) :: [Double] [0.5,0.7853981633974483,0.9159655941772191,0.9689461462593693,0.988944551741105]&(c) 2018 Andrew LelechenkoMIT/Andrew Lelechenko <andrew.lelechenko@gmail.com> ProvisionalNon-portable (GHC extensions)SafeV~ 5QRSTTUVWXYZ[\]^_`abcdefghijklmnopqrstuvvwxyz{|}~BC++++,.12 66666`_:::::::;;;;;;;;<<== = = = = ===>>>>>>>>>>>>>>>> >!>">#>$>%>&>'>(>)>>*>+>,>->.>/>0>1>2?3456@7@8@9@:B;<=>?@ABCDEFGHIJKLMNOPQRSTBCDUVWFGXJYZ[\]^_`abcdefghijklmnopqrFsFsFt u v!w!x!y!z!{!|!}!~!!!!!!HHHHHHHHHHHHHHHHHHHHHHHHHHHHHH"""""""""""""""""""#JJJJJJJJG$$%NNNN'''(((QRQRQRQRQRQRQRQRQRQRQRQRQRQRQRQQQ8QQQ**,,,,,,22444QQ 55555 5  5 5 555555555555QQ\6Q]99 9!9"9#9$9%Q&:':(:):*:+:,:-:.:/:01<2<3456457=8=9=:=;><>=>>?>@>A>B>C>D>E>F>G>H>I>J>K>L>M>N>O>P>Q>R>S>T>U>V>WXYZ[\]^_`abcdaeFf#g%hMiQYMjMkl(mn'arithmoi-0.8.0.0-6Rtnbx2jJER74A6C7rjrHdMath.NumberTheory.Moduli.ClassMath.NumberTheory.Euclidean$Math.NumberTheory.Euclidean.Coprimes!Math.NumberTheory.Primes.Counting%Math.NumberTheory.UniqueFactorisation%Math.NumberTheory.Recurrencies.Linear'Math.NumberTheory.Recurrencies.BilinearMath.NumberTheory.Recurrencies Math.NumberTheory.Powers.SquaresMath.NumberTheory.Powers.FourthMath.NumberTheory.Powers.Cubes&Math.NumberTheory.MoebiusInversion.Int"Math.NumberTheory.MoebiusInversion Math.NumberTheory.Powers.GeneralMath.NumberTheory.Moduli.Jacobi Math.NumberTheory.Primes.Testing Math.NumberTheory.Moduli.ChineseMath.NumberTheory.GCD.LowLevelMath.NumberTheory.GCD#Math.NumberTheory.Curves.MontgomeryMath.NumberTheory.Primes.SieveMath.NumberTheory.SmoothNumbersMath.NumberTheory.Moduli.Sqrt&Math.NumberTheory.Primes.Factorisation-Math.NumberTheory.Primes.Testing.Certificates0Math.NumberTheory.Primes.Factorisation.Certified Math.NumberTheory.Powers.Modular,Math.NumberTheory.Quadratic.GaussianIntegers.Math.NumberTheory.Quadratic.EisensteinIntegersMath.NumberTheory.Prefactored%Math.NumberTheory.ArithmeticFunctions"Math.NumberTheory.Moduli.Equations-Math.NumberTheory.ArithmeticFunctions.Moebius&Math.NumberTheory.Moduli.PrimitiveRoot*Math.NumberTheory.Moduli.DiscreteLogarithm0Math.NumberTheory.ArithmeticFunctions.SieveBlock-Math.NumberTheory.ArithmeticFunctions.MertensMath.NumberTheory.ZetaMath.NumberTheory.Zeta.Riemann Math.NumberTheory.Zeta.DirichletGHC.TypeNats.Compat)Math.NumberTheory.Powers.Squares.Internal-Math.NumberTheory.Primes.Counting.ApproximateMath.NumberTheory.Primes.TypesMath.Combinat.NumbersbinomialunsignedStirling1st stirling2nd bernoulli)Math.NumberTheory.Recurrencies.PentagonalMath.NumberTheory.Unsafe'Math.NumberTheory.Primes.Sieve.IndexingMath.NumberTheory.Utils.Math.NumberTheory.Primes.Testing.ProbabilisticNumeric.NaturalNatural$Math.NumberTheory.Utils.FromIntegral+Math.NumberTheory.Primes.Sieve.Eratosthenes Math.NumberTheory.Moduli.SqrtOld4Math.NumberTheory.Primes.Factorisation.TrialDivision1Math.NumberTheory.Primes.Factorisation.Montgomery6Math.NumberTheory.Primes.Testing.Certificates.Internal*Math.NumberTheory.Primes.Testing.Certified&Math.NumberTheory.Primes.Counting.ImplMath.NumberTheory.PrimespowMod powSomeModMath.NumberTheory.Powers"Math.NumberTheory.GaussianIntegers+Math.NumberTheory.ArithmeticFunctions.ClasssieveBlockUnboxed.Math.NumberTheory.ArithmeticFunctions.StandardMath.NumberTheory.Moduli8Math.NumberTheory.ArithmeticFunctions.SieveBlock.UnboxedDataVector!Math.NumberTheory.Utils.HyperbolaMath.NumberTheory.Zeta.UtilsData.Number.FixedFixedbase GHC.TypeNatsKnownNatWrappedIntegralunWrappedIntegral EuclideanquotRemdivModquotremdivmodgcdlcmcoprime extendedGCD$fEuclideanNatural$fEuclideanInteger$fEuclideanWord$fEuclideanInt$fEuclideanWrappedIntegral$fEqWrappedIntegral$fOrdWrappedIntegral$fShowWrappedIntegral$fNumWrappedIntegral$fIntegralWrappedIntegral$fRealWrappedIntegral$fEnumWrappedIntegralCoprimes unCoprimes singletoninsertsplitIntoCoprimes$fMonoidCoprimes$fSemigroupCoprimes $fEqCoprimes$fShowCoprimesSomeModInfModMultMod multElementModgetMod getNatModgetVal getNatVal invertMod^% isMultElement invertGroupmodulo invertSomeMod$fFractionalMod$fNumMod $fBoundedMod $fShowMod$fBoundedMultMod$fMonoidMultMod$fSemigroupMultMod$fFractionalSomeMod $fNumSomeMod $fShowSomeMod $fEqSomeMod$fEqMod$fOrdMod $fEnumMod $fEqMultMod $fOrdMultMod $fShowMultMod!approxPrimeCountOverestimateLimitapproxPrimeCount nthPrimeApproxUnderestimateLimitnthPrimeApproxPrime factorial fibonacci fibonacciPairlucas lucasPair generalLucas stirling1 stirling2lah eulerian1 eulerian2euler eulerPolyAt1 partitionintegerSquareRootintegerSquareRoot'integerSquareRootRemintegerSquareRootRem'exactSquareRootisSquare isSquare'isPossibleSquareisPossibleSquare2integerFourthRootintegerFourthRoot'exactFourthRoot isFourthPowerisFourthPower'isPossibleFourthPowerintegerCubeRootintegerCubeRoot' exactCubeRootisCubeisCube'isPossibleCube totientSumgeneralInversion integerRoot exactRoot isKthPowerisPerfectPower highestPower largePFPower JacobiSymbolMinusOneZeroOnejacobijacobi'$fMonoidJacobiSymbol$fSemigroupJacobiSymbol$fEqJacobiSymbol$fOrdJacobiSymbol$fShowJacobiSymbolisPrime millerRabinVisStrongFermatPP isFermatPP bailliePSWchineseRemainderchineseRemainder2gcdInt coprimeIntgcdWord coprimeWordgcdInt# coprimeInt#gcdWord# coprimeWord# binaryGCD SomePointPointpointXpointZpointA24pointNnewPointadddoublemultiply $fShowPoint $fEqPoint$fShowSomePoint PrimeSieve primeSieve primeListprimes psieveList sieveFrom psieveFrom SmoothBasisfromSetfromListfromSmoothUpperBound smoothOversmoothOverInRangesmoothOverInRangeBF$fEqSmoothBasis$fShowSmoothBasissqrtModP sqrtModPList sqrtModP' tonelliShanks sqrtModPPsqrtModF sqrtModFList sqrtModPPListtrialDivisionTotrialDivisionPrimeTo factorise factorise'stepFactorisationdefaultStdGenFactorisationdefaultStdGenFactorisation'stdGenFactorisationcurveFactorisationmontgomeryFactorisation smallFactorsPrimalityArgumentPockDivisionObvious Assumptionaprime largeFactor smallFactor factorListalimitPrimalityProofcprimeCompositenessArgumentDivisorsFermatLucasBeliefcompo firstDivisor secondDivisor fermatBaseCompositenessProof composite Certificate CompositeargueCertificatearguePrimalityverifyPrimalityArgumentargueCompositenessverifyCompositenessArgumentcheckCertificatecheckCompositenessProofcheckPrimalityProofcertifyisCertifiedPrimecertifiedFactorisationcertificateFactorisationprovenFactorisationprimeCountMaxArg primeCountnthPrimeMaxArgnthPrime powModWord powModIntsqrtsModsqrtsModFactorisationsqrtsModPrimePower sqrtsModPrimeGaussianInteger:+realimagι conjugatenormgcdGgcdG' findPrime findPrime'.^$fEuclideanGaussianInteger$fNumGaussianInteger$fShowGaussianInteger$fNFDataGaussianInteger$fEqGaussianInteger$fOrdGaussianInteger$fGenericGaussianIntegerEisensteinIntegerωids associates divideByThree$fEuclideanEisensteinInteger$fNumEisensteinInteger$fShowEisensteinInteger$fEqEisensteinInteger$fOrdEisensteinInteger$fGenericEisensteinIntegerUniqueFactorisationunPrime&$fUniqueFactorisationEisensteinInteger$$fUniqueFactorisationGaussianInteger$fUniqueFactorisationNatural$fUniqueFactorisationInteger$fUniqueFactorisationWord$fUniqueFactorisationInt$fEqGaussianPrime$fShowGaussianPrime$fEqEisensteinPrime$fShowEisensteinPrime Prefactored prefValue prefFactors fromValue fromFactors $fUniqueFactorisationPrefactored$fNumPrefactored$fShowPrefactoredArithmeticFunction runFunction solveLinearsolveQuadraticMoebiusMoebiusNMoebiusZMoebiusP runMoebiussieveBlockMoebius$fMonoidMoebius$fSemigroupMoebius$fVectorVectorMoebius$fMVectorMVectorMoebius$fUnboxMoebius $fEqMoebius $fOrdMoebius $fShowMoebiusmultiplicativedivisors divisorsA divisorsList divisorsListA divisorsSmalldivisorsSmallAtautauAsigmasigmaAtotienttotientAjordanjordanA ramanujan ramanujanAmoebiusmoebiusA liouville liouvilleA carmichael carmichaelAadditive smallOmega smallOmegaAbigOmega bigOmegaA expMangoldt expMangoldtA PrimitiveRootunPrimitiveRootgetGroup CyclicGroupCG2CG4CGOddPrimePowerCGDoubleOddPrimePowercyclicGroupFromModulocyclicGroupToModuloisPrimitiveRoot'isPrimitiveRoot groupSize$fNFDataCyclicGroup$fGenericCyclicGroup$fEqPrimitiveRoot$fShowPrimitiveRoot$fShowCyclicGroup$fEqCyclicGroupdiscreteLogarithmSieveBlockConfigsbcEmptysbcFunctionOnPrimePower sbcAppendmultiplicativeSieveBlockConfigadditiveSieveBlockConfigrunFunctionOverBlock sieveBlockmertens intertwineskipOdds skipEvenssuminf zetasEvenzetasOddzetasbetasOdd betasEvenbetasghc-prim GHC.TypesNat+*^<=?-CmpNatDivLog2sameNat someNatValnatVal'natValSomeNat<=GHC.RealIntegral toInteger GHC.NaturalGHC.EnumminBoundGHC.NumNum FractionalisqrtA karatsubaSqrtPrimeNat unPrimeNatPrmunPrmeuler'helperForB_E_EPpentspentagonalSigns array-0.5.2.0Data.Array.Base castSTUArray unsafeThaw unsafeFreezeunsafeAtboundsUArray unsafeWrite unsafeReadunsafeNewArray_idxPrtoPrimrhoGHC.BaseNothingJustappCuRtIntshiftToOddCount shiftOCWordWord shiftOCIntshiftOCInteger integer-gmpGHC.Integer.TypeIntegershiftOCNaturalbigNatZeroCountBigNat shiftToOdd shiftOInt shiftOWord shiftOInteger shiftToOdd#shiftToOddCount# bitCountWord#GHC.PrimWord# bitCountWord bitCountInt splitOff#splitOffmergeByrecipModuncheckedShiftRabs lucasTestInt# wordToInt wordToInteger intToWord intToIntegernaturalToIntegerintegerToNatural integerToWordmaxBound doesNotFittakeWhileIncreasingsieveToPS sieveBits sieveRange countFromTo nthPrimeCt countToNthcountAllisValidtrialDivisionWithtrialDivisionPrimeWith!random-1.1-9LLJAJa4iQFLJiLXBOBXBV System.RandomStdGenrandomRbigStepenumAndMultiplyFromThenTo testParms findParms primProof compProofFalsetrivial maybeTrivialisTrivialPrime trivialPrimes smallCert certifyBPSWfindDecomposition findFactorfindLoop bpswMessagefoundfermat TrialDivision PocklingtonTrivialfactorisedPartcofactor knownFactorstdLimitFactors StrongFermatLucasSelfridge firstFactor secondFactorwitnesstest primeCheckcertiFactorisationmergemergeAllinvalidsqrtOfMinusOne sqrtModPP' divideByTwo divideByPrime absSignumprimary divHelper quotEvenI$fNumArithmeticFunctiondiscreteLogarithm'sumMultMoebiuspointsUnderHyperbola0stepBackpointsUnderHyperbolaDouble betasOdd'