!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~                !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~None6BM 2Infinite list of primes, using the TMWE algorithm.YA relatively simple but still quite fast implementation of list of primes. By Will Ness Ghttp://www.haskell.org/pipermail/haskell-cafe/2009-November/068441.html?List of primes, using tree merge with wheel. Code by Will Ness.TGroups integer factors. Example: from [2,2,2,3,3,5] we produce [(2,3),(3,2),(5,1)] #The naive trial division algorithm.Largest integer k such that 2^k is smaller or equal to nSmallest integer k such that 2^k is larger or equal to nInteger square root (largest integer whose square is smaller or equal to the input) using Newton's method, with a faster (for large numbers) inital guess based on bit shifts. =Smallest integer whose square is larger or equal to the input *We also return the excess residue; that is (a,r) = integerSquareRoot' n means that "a*a + r = n a*a <= n < (a+1)*(a+1) xNewton's method without an initial guess. For very small numbers (<10^10) it is somewhat faster than the above version. Efficient powers modulo m. powerMod a k m == (a^k) `mod` m eMiller-Rabin Primality Test (taken from Haskell wiki). We test the primality of the first argument n by using the second argument a' as a candidate witness. If it returs False, then n is composite. If it returns True, then n is either prime or composite.A random choice between 2 and (n-2) is a good choice for a.    None6BM MThe series [1,0,0,0,0,...], which is the neutral element for the convolution.TConvolution of series. The result is always an infinite list. Warning: This is slow!'Convolution of many series. Still slow!Power series expansion of  /1 / ( (1-x^k_1) * (1-x^k_2) * ... * (1-x^k_n) )Example:(coinSeries [2,3,5])!!k is the number of ways to pay k3 dollars with coins of two, three and five dollars.TODO: better name?BGeneralization of the above to include coefficients: expansion of <1 / ( (1-a_1*x^k_1) * (1-a_2*x^k_2) * ... * (1-a_n*x^k_n) ) Convolution of many G, that is, the expansion of the reciprocal of a product of polynomialsThe same, with coefficients.bThis is the most general function in this module; all the others are special cases of this one. The power series expansion of -1 / (1 - x^k_1 - x^k_2 - x^k_3 - ... - x^k_n)!Convolve with (the expansion of) -1 / (1 - x^k_1 - x^k_2 - x^k_3 - ... - x^k_n)The expansion of =1 / (1 - a_1*x^k_1 - a_2*x^k_2 - a_3*x^k_3 - ... - a_n*x^k_n)!Convolve with (the expansion of) =1 / (1 - a_1*x^k_1 - a_2*x^k_2 - a_3*x^k_3 - ... - a_n*x^k_n)"!Convolve with (the expansion of)  21 / (1 +- x^k_1 +- x^k_2 +- x^k_3 +- ... +- x^k_n)Should be faster than using  . Note:  corresponds to the coefficient -1 in 8 (since there is a minus sign in the definition there)! !" !" !" !"None6BM.The boolean argument will True only for the last element18extend lines with spaces so that they have the same line#$%&'()*+,-./0123456789:;<=>?@#$%&'()*+,-./0123456789:;<=>?@#$%&'()*+,-./0123456789:;<=>?@#$%&'()*+,-./0123456789:;<=>?@None6BMAH"Tuples" fitting into a give shape. The order is lexicographic, that is, &sort ts == ts where ts = tuples' shape Example: \tuples' [2,3] = [[0,0],[0,1],[0,2],[0,3],[1,0],[1,1],[1,2],[1,3],[2,0],[2,1],[2,2],[2,3]]B,positive "tuples" fitting into a give shape.C# = \prod_i (m_i + 1)D# = \prod_i m_iG# = (m+1) ^ lenH # = m ^ len ABCDElength (width)maximum (height)Flength (width)maximum (height)GHI ABCDEFGHI ABCDEFGHI ABCDEFGHINone6BMJ (-1)^kKA000142.LA006882.MA007318.NA given row of the Pascal triangle; equivalent to a sequence of binomial numbers, but much more efficient. You can also left-fold over it. +pascalRow n == [ binomial n k | k<-[0..n] ]PCatalan numbers. OEIS:A000108.Q(Catalan's triangle. OEIS:A009766. Note: fcatalanTriangle n n == catalan n catalanTriangle n k == countStandardYoungTableaux (toPartition [n,k])RcRows of (signed) Stirling numbers of the first kind. OEIS:A008275. Coefficients of the polinomial (x-1)*(x-2)*...*(x-n+1),. This function uses the recursion formula.SO(Signed) Stirling numbers of the first kind. OEIS:A008275. This function uses R&, so it shouldn't be used to compute many Stirling numbers.Argument order: signedStirling1st n kT3(Unsigned) Stirling numbers of the first kind. See S.U[Stirling numbers of the second kind. OEIS:A008277. This function uses an explicit formula.Argument order: stirling2nd n kVBernoulli numbers. bernoulli 1 == -1%2 and bernoulli k == 0 for k>2 and odd|. This function uses the formula involving Stirling numbers of the second kind. Numerators: A027641, denominators: A027642.WPBell numbers (Sloane's A000110) from B(0) up to B(n). B(0)=B(1)=1, B(2)=2, etc. %The Bell numbers count the number of set partitions of a set of size nSee (http://en.wikipedia.org/wiki/Bell_numberXiThe n-th Bell number B(n), using the Stirling numbers of the second kind. This may be slower than using W.JKLMNOPQRSTUVWXJKLMNOPQRSTUVWXJKLMNOPQRSTUVWXJKLMNOPQRSTUVWXNone6BM YAll possible ways to choose kZ elements from a list, without repetitions. "Antisymmetric power" for lists. Synonym for _.Z choose_ k n' returns all possible ways of choosing k disjoint elements from [1..n] choose_ k n == choose k [1..n][All possible ways to choose k elements from a list, with repetitions*. "Symmetric power" for lists. See also Math.Combinat.Compositions. TODO: better name?\A synonym for [.]*"Tensor power" for lists. Special case of ^: 2tuplesFromList k xs == listTensor (replicate k xs) See also Math.Combinat.Tuples. TODO: better name?^"Tensor product" for lists._3Sublists of a list having given number of elements.`# = binom { n } { k }.aAll sublists of a list.b# = 2^n.crandomChoice k n& returns a uniformly random choice of k elements from the set [1..n]Example: Zdo cs <- replicateM 10000 (getStdRandom (randomChoice 3 7)) mapM_ print $ histogram cs?From a list of $k$ numbers, where the first is in the interval [1..n], the second in [1..n-1], the third in [1..n-2], we create a size k subset of n. YZ[\]^_`abc YZ[\]^_`abc YZ[\]^_a`bc YZ[\]^_`abcNone6BM dA  composition of an integer n into k parts is an ordered kB-tuple of nonnegative (sometimes positive) integers whose sum is n.ekCompositions fitting into a given shape and having a given degree. The order is lexicographic, that is, .sort cs == cs where cs = compositions' shape kgbAll positive compositions of a given number (filtrated by the length). Total number of these is 2^(n-1)h,All compositions fitting into a given shape.i+Nonnegative compositions of a given length.j # = \binom { len+d-1 } { len-1 }k(Positive compositions of a given length.mrandomComposition k n8 returns a uniformly random composition of the number n as an (ordered) sum of k  nonnegative numbersnrandomComposition1 k n8 returns a uniformly random composition of the number n as an (ordered) sum of k positive numbers deshapesumfghilengthsumjklengthsumlmn defghijklmn defghijklmn defghijklmnNone6BMo,Integer vectors. The indexing starts from 1.rA partition of an integer. The additional invariant enforced here is that partitions are monotone decreasing sequences of positive integers.s3Sorts the input, and cuts the nonpositive elements.t%Assumes that the input is decreasing.uBChecks whether the input is an integer partition. See the note at v!v9Note: we only check that the sequence is ordered, but we do not} check for negative elements. This can be useful when working with symmetric functions. It may also change in the future...x"The first element of the sequence.yThe length of the sequence.{QThe weight of the partition (that is, the sum of the corresponding sequence).|"The dual (or conjugate) partition.~Example: lelements (toPartition [5,4,1]) == [ (1,1), (1,2), (1,3), (1,4), (1,5) , (2,1), (2,2), (2,3), (2,4) , (3,1) ]DComputes the number of "automorphisms" of a given integer partition.Integer partitions of d+, fitting into a given rectangle, as lists.RPartitions of d, fitting into a given rectangle. The order is again lexicographic.Partitions of d , as listsPartitions of d.6All integer partitions fitting into a given rectangle.kAll integer partitions up to a given degree (that is, all integer partitions whose sum is less or equal to d)# = \binom { h+w } { h }Lists partitions of n into k parts. Xsort (partitionsWithKParts k n) == sort [ p | p <- partitions n , numberOfParts p == k ]Naive recursive algorithm. Synonym for Partitions of a multiset.+Vector partitions. Basically a synonym for .jGenerates all vector partitions ("algorithm M" in Knuth). The order is decreasing lexicographic. +opqrstuvwxyz{|}~(height,width)d(height,width)d(height,width)k = number of partsn = the integer we partitionk = number of partsn = the integer we partition)opqrstuvwxyz{|}~)rutsvwxyz{|}~pqo)opqrstuvwxyz{|}~ None6BM;Disjoint cycle notation for permutations. Internally it is [[Int]].NStandard notation for permutations. Internally it is an array of the integers [1..n]. 7Assumes that the input is a permutation of the numbers [1..n].9Checks whether the input is a permutation of the numbers [1..n].Checks the input.Returns n2, where the input is a permutation of the numbers [1..n] This is compatible with Maple's convert(perm,'disjcyc'). Plus 1 or minus 1.TAction of a permutation on a set. If our permutation is encoded with the sequence [p1,p2,...,pn](, then in the two-line notation we have '( 1 2 3 ... n ) ( p1 p2 p3 ... pn ).We adopt the convention that permutations act  on the left> (as opposed to Knuth, where they act on the right). Thus,  Apermute pi1 (permute pi2 set) == permute (pi1 `multiply` pi2) set3The second argument should be an array with bounds (1,n)(. The function checks the array bounds.The list should be of length n.*Multiplies two permutations together. See  for our conventions. The inverse permutation.The trivial permutation.A synonym for Permutations of [1..n]) in lexicographic order, naive algorithm.# = n!A synonym for .A synonym for .,Generates a uniformly random permutation of [1..n] . Durstenfeld's algorithm (see  *http://en.wikipedia.org/wiki/Knuth_shuffle).Generates a uniformly random cyclic permutation of [1..n]. Sattolo's algorithm (see  *http://en.wikipedia.org/wiki/Knuth_shuffle).YGenerates all permutations of a multiset. The order is lexicographic. A synonym for 3# = \frac { (sum_i n_i) ! } { \prod_i (n_i !) } Generates all permutations of a multiset (based on "algorithm L" in Knuth; somewhat less efficient). The order is lexicographic. '$$% None6BM An element (i,j)x of the resulting tableau (which has shape of the given partition) means that the vertical part of the hook has length i, and the horizontal part j. The  hook length is thus i+j-1. Example: m> mapM_ print $ hooks $ toPartition [5,4,1] [(3,5),(2,4),(2,3),(2,2),(1,1)] [(2,4),(1,3),(1,2),(1,1)] [(1,1)]OStandard Young tableaux of a given shape. Adapted from John Stembridge,  ?http://www.math.lsa.umich.edu/~jrs/software/SFexamples/tableaux.hook-length formulaASemistandard Young tableaux of given shape, "naive" algorithm +Stanley's hook formula (cf. Fulton page 55) None6BMSet of (i,j) pairs with i>=j>=1.Triangular arraysGenerates all tableaux of size k. Effective for k<=6.  None6BMA partition of the set [1..n] (in standard order) Synonym for  Synonym for  ^sort (setPartitionsWithKParts k n) == sort [ p | p <- setPartitions n , numberOfParts p == k ]List all set partitions of [1..n], naive algorithmSet partitions of the set [1..n] into k parts.Set partitions are counted by the Bell numbersSet partitions of size k3 are counted by the Stirling numbers of second kindk = number of partsn = size of the setk = number of partsn = size of the setk = number of partsn = size of the set   None6BMDA binary tree with leaves and internal nodes decorated with types a and b, respectively..A binary tree with leaves decorated with type a.+Convert a binary tree to a rose tree (from  Data.Tree)8Generates all sequences of nested parentheses of length 2n in lexigraphic order. Synonym for . Synonym for . Synonym for .Generates all sequences of nested parentheses of length 2n. Order is lexicographical (when right parentheses are considered smaller then left ones). Based on "Algorithm P" in Knuth, but less efficient because of the "idiomatic" code.oGenerates a uniformly random sequence of nested parentheses of length 2n. Based on "Algorithm W" in Knuth.ONth sequence of nested parentheses of length 2n. The order is the same as in #. Based on "Algorithm U" in Knuth.NGenerates all binary trees with n nodes. At the moment just a synonym for .9# = Catalan(n) = \frac { 1 } { n+1 } \binom { 2n } { n }.FThis is also the counting function for forests and nested parentheses.=Generates all binary trees with n nodes. The naive algorithm.1Generates an uniformly random binary tree, using .Grows a uniformly random binary tree. "Algorithm R" (Remy's procudere) in Knuth. Nodes are decorated with odd numbers, leaves with even numbers (from the set [0..2n]"). Uses mutable arrays internally.3Draws a binary tree in ASCII, ignoring node labels.Example: &mapM_ printBinaryTree_ $ binaryTrees 4)n!N; should satisfy 1 <= N <= C(n) *%#None6BM ]A lattice path is a path using only the allowed steps, never going below the zero level line y=0. nNote that if you rotate such a path by 45 degrees counterclockwise, you get a path which uses only the steps (1,0) and (0,1)Z, and stays above the main diagonal (hence the name, we just use a different convention). A step in a lattice path  the step (1,-1)  the step (1,1) =A lattice path is called "valid", if it never goes below the y=0 line.;A Dyck path is a lattice path whose last point lies on the y=0 line Maximal height of a lattice path.Endpoint of a lattice path, which starts from (0,0).BReturns the coordinates of the path (excluding the starting point (0,0), but including the endpoint)2Number of peaks of a path (excluding the endpoint)-Number of points on the path which touch the y=00 zero level line (excluding the starting point (0,0)S, but including the endpoint; that is, for Dyck paths it this is always positive!).BNumber of points on the path which touch the level line at height h (excluding the starting point (0,0), but including the endpoint). dyckPaths m lists all Dyck paths from (0,0) to (2m,0). hRemark: Dyck paths are obviously in bijection with nested parentheses, and thus also with binary trees.!Order is reverse lexicographical: +sort (dyckPaths m) == reverse (dyckPaths m) dyckPaths m lists all Dyck paths from (0,0) to (2m,0).  .sort (dyckPathsNaive m) == sort (dyckPaths m) *Naive recursive algorithm, order is ad-hocThe number of Dyck paths from (0,0) to (2m,0)# is simply the m'th Catalan number.The trivial bijection,The trivial bijection in the other directionboundedDyckPaths h m lists all Dyck paths from (0,0) to (2m,0) whose height is at most h. Synonym for .boundedDyckPathsNaive h m lists all Dyck paths from (0,0) to (2m,0) whose height is at most h. sort (boundedDyckPaths h m) == sort [ p | p <- dyckPaths m , pathHeight p <= h ] sort (boundedDyckPaths m m) == sort (dyckPaths m) <Naive recursive algorithm, resulting order is pretty ad-hoc.All lattice paths from (0,0) to (x,y). Clearly empty unless x-y is even. Synonym for All lattice paths from (0,0) to (x,y). Clearly empty unless x-y is even. Note that 1sort (dyckPaths n) == sort (latticePaths (0,2*n))<Naive recursive algorithm, resulting order is pretty ad-hoc.touchingDyckPaths k m lists all Dyck paths from (0,0) to (2m,0)# which touch the zero level line y=0 exactly kI times (excluding the starting point, but including the endpoint; thus, k" should be positive). Synonym for .touchingDyckPathsNaive k m lists all Dyck paths from (0,0) to (2m,0)# which touch the zero level line y=0 exactly kI times (excluding the starting point, but including the endpoint; thus, k should be positive). csort (touchingDyckPathsNaive k m) == sort [ p | p <- dyckPaths m , pathNumberOfZeroTouches p == k ]<Naive recursive algorithm, resulting order is pretty ad-hoc. peakingDyckPaths k m lists all Dyck paths from (0,0) to (2m,0) with exactly k peaks. Synonym for !!peakingDyckPathsNaive k m lists all Dyck paths from (0,0) to (2m,0) with exactly k peaks. [sort (peakingDyckPathsNaive k m) = sort [ p | p <- dyckPaths m , pathNumberOfPeaks p == k ]<Naive recursive algorithm, resulting order is pretty ad-hoc."Dyck paths of length 2m with k+ peaks are counted by the Narayana numbers &N(m,k) = binom{m}{k} binom{m}{k-1} / m#'A uniformly random Dyck path of length 2m     h = the touch levelh = maximum heightm = half-lengthh = maximum heightm = half-lengthk = number of touchesm = half-lengthk = number of touchesm = half-length k = number of peaksm = half-length!k = number of peaksm = half-length"k = number of peaksm = half-length#      !"#      !"#      !"#None6BM$$A non-crossing partition of the set [1..n]t in standard form: entries decreasing in each block and blocks listed in increasing order of their first entries.&.Checks whether a set partition is noncrossing.Implementation method: we convert to a Dyck path and then back again, and finally compare. Probably not very efficient, but should be better than a naive check for crosses...)'5Warning: This function assumes the standard ordering!(zConvert to standard form: entries decreasing in each block and blocks listed in increasing order of their first entries.+<Throws an error if the input is not a non-crossing partition-CIf a set partition is actually non-crossing, then we can convert it.7Bijection between Dyck paths and noncrossing partitionsBased on: David Callan: &Sets, Lists and Noncrossing Partitions&Fails if the input is not a Dyck path./Safe version of .00The inverse bijection (should never fail proper $-s)1 Safe version 02%Lists all non-crossing partitions of [1..n]XEquivalent to (but orders of magnitude faster than) filtering out the non-crossing ones: f(sort $ catMaybes $ map setPartitionToNonCrossing $ setPartitions n) == sort (nonCrossingPartitions n)3%Lists all non-crossing partitions of [1..n] into k parts. nsort (nonCrossingPartitionsWithKParts k n) == sort [ p | p <- nonCrossingPartitions n , numberOfParts p == k ]4:Non-crossing partitions are counted by the Catalan numbers5Non-crossing partitions with k* parts are counted by the Naranaya numbers6'Uniformly random non-crossing partition$%&'()*+,-./0123k = number of parts n = size of the set45k = number of parts n = size of the set67$%&'()*+,-./0123456$%&'()*+,-7./0123456$%&'()*+,-./01234567None6BM8regularNaryTrees d n' returns the list of (rooted) trees on n$ nodes where each node has exactly d0 children. Note that the leaves do not count in n. Naive algorithm.9Ternary trees on n nodes (synonym for regularNaryTrees 3):We have clength (regularNaryTrees d n) == countRegularNaryTrees d n == \frac {1} {(d-1)n+1} \binom {dn} {n} ; %# = \frac {1} {(2n+1} \binom {3n} {n}< All trees on nZ nodes where the number of children of all nodes is in element of the given set. Example: mapM_ printTreeVertical $ map labelNChildrenTree_ $ semiRegularTrees [2,3] n [ length $ semiRegularTrees [2,3] n | n<-[0..] ] == [1,2,10,66,498,4066,34970,312066,2862562,26824386,...](The latter sequence is A027307 in OEIS: https://oeis.org/A027307Remark: clearly, we have .semiRegularTrees [d] n == regularNaryTrees d n=1Vertical ASCII drawing of a tree, without labels.Example: 0mapM_ printTreeVertical_ $ regularNaryTrees 2 3 >Prints all labels. Example: HprintTreeVertical $ addUniqueLabelsTree_ $ (regularNaryTrees 3 9) !! 666?@Prints the labels for the leaves, but not for the nonempty nodes@Nodes are denoted by @ , leaves by *.ANodes are denoted by (label) , leaves by label.BNodes are denoted by @ , leaves by label.CDThe leftmost spine (the second element of the pair is the leaf node)E(The leftmost spine without the leaf nodeG/The length (number of edges) on the left spine 0leftSpineLength tree == length (leftSpine_ tree)I is leaf,  is nodeS8Adds unique labels to the nodes (including leaves) of a .T8Adds unique labels to the nodes (including leaves) of a W=Attaches the depth to each node. The depth of the root is 0. [.Attaches the number of children to each node. _fComputes the set of equivalence classes of rooted trees (in the sense that the leaves of a node are  unordered ) with  n = length ks| leaves where the set of heights of the leaves matches the given set of numbers. The height is defined as the number of edges from the leaf to the root. TODO: better name?)8(degree = number of children of each nodenumber of nodes9:;<!set of allowed number of childrennumber of nodes=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_(89:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_(98<;:_=>?@ABIJKLMNOPQRCEDFGHSTUVWXYZ[\]^)89:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_None6BMR89:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_None6BMcGenerates graphviz .dot file from a forest. The first argument tells whether to make the individual trees clustered subgraphs; the second is the name of the graph.dGenerates graphviz .dot@ file from a tree. The first argument is the name of the graph.`abc-make the individual trees clustered subgraphs#reverse the direction of the arrowsname of the graphd"reverse the direction of the arrowname of the graph`abcd`abdc`abcdNone6BFMeA wordy, describing (non-uniquely) an element of a group. The identity element is represented (among others) by the empty word.fA generator of a (free) groupiThe index of a generatorj'Generators are shown as small letters: a, b, c;, ... and their inverses are shown as capital letters, so A=a^-1, B=b^-1, etc.lThe inverse of a generatormThe inverse of a wordn:Lists all words of the given length (total number will be (2g)^n'). The numbering of the generators is [1..g].ocLists all words of the given length which do not contain inverse generators (total number will be g^n'). The numbering of the generators is [1..g].p2A random group generator (or its inverse) between 1 and gq9A random group generator (but never its inverse) between 1 and grA random word of length n using g generators (or their inverses)sA random word of length n using g$ generators (but not their inverses)tkMultiplication of the free group (returns the reduced result). It is true for any two words w1 and w2 that EmultiplyFree (reduceWordFree w1) (reduceWord w2) = multiplyFree w1 w2u6Reduces a word in a free group by repeatedly removing x*x^(-1) and x^(-1)*x pairs. The set of  reduced words^ forms the free group; the multiplication is obtained by concatenation followed by reduction.v%Counts the number of words of length n& which reduce to the identity element.Generating function is 9Gf_g(u) = \frac {2g-1} { g-1 + g \sqrt{ 1 - (8g-4)u^2 } }w%Counts the number of words of length n whose reduced form has length k (clearly n and k3 must have the same parity for this to be nonzero): ^countWordReductionsFree g n k == sum [ 1 | w <- allWords g n, k == length (reduceWordFree w) ]x'Multiplication in free products of Z2'sy'Multiplication in free products of Z3'sz'Multiplication in free products of Zm's{%Reduces a word, where each generator x# satisfies the additional relation x^2=1" (that is, free products of Z2's)|%Reduces a word, where each generator x# satisfies the additional relation x^3=1" (that is, free products of Z3's)}%Reduces a word, where each generator x# satisfies the additional relation x^m=1" (that is, free products of Zm's)~BCounts the number of words (without inverse generators) of length n= which reduce to the identity element, using the relations x^2=1.Generating function is 9Gf_g(u) = \frac {2g-2} { g-2 + g \sqrt{ 1 - (4g-4)u^2 } }The first few g cases: A000984 = [ countIdentityWordsZ2 2 (2*n) | n<-[0..] ] = [1,2,6,20,70,252,924,3432,12870,48620,184756...] A089022 = [ countIdentityWordsZ2 3 (2*n) | n<-[0..] ] = [1,3,15,87,543,3543,23823,163719,1143999,8099511,57959535...] A035610 = [ countIdentityWordsZ2 4 (2*n) | n<-[0..] ] = [1,4,28,232,2092,19864,195352,1970896,20275660,211823800,2240795848...] A130976 = [ countIdentityWordsZ2 5 (2*n) | n<-[0..] ] = [1,5,45,485,5725,71445,925965,12335685,167817405,2321105525,32536755565...]BCounts the number of words (without inverse generators) of length nJ whose reduced form in the product of Z2-s (that is, for each generator x we have x^2=1) has length k (clearly n and k3 must have the same parity for this to be nonzero): _countWordReductionsZ2 g n k == sum [ 1 | w <- allWordsNoInv g n, k == length (reduceWordZ2 w) ]BCounts the number of words (without inverse generators) of length n= which reduce to the identity element, using the relations x^3=1. acountIdentityWordsZ3NoInv g n == sum [ 1 | w <- allWordsNoInv g n, 0 == length (reduceWordZ2 w) ] In mathematica, the formula is: BSum[ g^k * (g-1)^(n-k) * k/n * Binomial[3*n-k-1, n-k] , {k, 1,n} ]efghijklmng = number of generators n = length of the wordog = number of generators n = length of the wordpg = number of generators qg = number of generators rg = number of generators n = length of the wordsg = number of generators n = length of the wordtuv*g = number of generators in the free group n = length of the unreduced wordw*g = number of generators in the free group n = length of the unreduced wordk = length of the reduced wordxyz{|}~*g = number of generators in the free group n = length of the unreduced word*g = number of generators in the free group n = length of the unreduced wordk = length of the reduced word*g = number of generators in the free group n = length of the unreduced wordefghijklmnopqrstuvwxyz{|}~fhgiejklmnopqrstuvwxyz{|}~efhgijklmnopqrstuvwxyz{|}~None6BMABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~      !"#89:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~                                              !"#$%&'()*+,-./01234567789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~                          combinat-0.2.6.2Math.Combinat.Numbers.PrimesMath.Combinat.Numbers.SeriesMath.Combinat.HelperMath.Combinat.TuplesMath.Combinat.NumbersMath.Combinat.SetsMath.Combinat.CompositionsMath.Combinat.PartitionsMath.Combinat.PermutationsMath.Combinat.TableauxMath.Combinat.Tableaux.KostkaMath.Combinat.Partitions.SetMath.Combinat.Trees.BinaryMath.Combinat.LatticePaths$Math.Combinat.Partitions.NonCrossingMath.Combinat.Trees.NaryMath.Combinat.GraphvizMath.Combinat.FreeGroupsMath.Combinat.Trees Math.Combinatprimes primesSimple primesTMWEgroupIntegerFactorsintegerFactorsTrialDivision integerLog2 ceilingLog2isSquareintegerSquareRootceilingSquareRootintegerSquareRoot'integerSquareRootNewton'powerModmillerRabinPrimalityTestSignMinusPlus unitSeriesconvolve convolveMany coinSeries coinSeries'convolveWithCoinSeriesconvolveWithCoinSeries'productPSeriesproductPSeries'convolveWithProductPSeriesconvolveWithProductPSeries'pseriesconvolveWithPSeriespseries'convolveWithPSeries' signValue signedPSeriesconvolveWithSignedPSeriesdebugswappairs pairsWithsum'equatingreverseOrderingreverseCompare reverseSort groupSortBynubOrd mapWithLast mapWithFirstmapWithFirstLastmkLinesUniformWidthmkBlocksUniformHeightmkUniformBlocks hConcatLines vConcatLinescount histogramfromJust intToBool boolToIntnestunfold1unfold unfoldEitherunfoldM mapAccumMtuples'tuples1' countTuples' countTuples1'tuplestuples1 countTuples countTuples1 binaryTuples paritySign factorialdoubleFactorialbinomial pascalRow multinomialcatalancatalanTrianglesignedStirling1stArraysignedStirling1stunsignedStirling1st stirling2nd bernoullibellNumbersArray bellNumberchoosechoose_combinecomposetuplesFromList listTensor kSublistscountKSublistssublists countSublists randomChoice Composition compositions'countCompositions'allCompositions1allCompositions' compositionscountCompositions compositions1countCompositions1randomCompositionrandomComposition1 IntVectorHasNumberOfParts numberOfParts Partition mkPartitiontoPartitionUnsafe toPartition isPartition fromPartitionheightwidth heightWidthweight dualPartition_dualPartitionelements _elementscountAutomorphisms_countAutomorphisms _partitions' partitions'countPartitions' _partitions partitionscountPartitionsallPartitions' allPartitionscountAllPartitions'countAllPartitionspartitionsWithKPartscountPartitionsWithKPartsprintFerrerDiagram ferrerDiagramferrerDiagramEnglishNotationferrerDiagramFrenchNotationferrerDiagramEnglishNotation'ferrerDiagramFrenchNotation'partitionMultisetvectorPartitions_vectorPartitionsfasc3B_algorithm_MDisjointCycles PermutationfromPermutationpermutationArraytoPermutationUnsafearrayToPermutationUnsafe isPermutation toPermutationpermutationSizefromDisjointCyclesdisjointCyclesUnsafedisjointCyclesToPermutationpermutationToDisjointCyclesisEvenPermutationisOddPermutationsignOfPermutationisCyclicPermutationpermute permuteListmultiplyinverseidentity permutations _permutationspermutationsNaive_permutationsNaivecountPermutationsrandomPermutation_randomPermutationrandomCyclicPermutation_randomCyclicPermutationrandomPermutationDurstenfeldrandomCyclicPermutationSattolopermuteMultisetcountPermuteMultisetfasc2B_algorithm_LTableau_shapeshape dualTableaucontenthooks hookLengthsrowWordrowWordToTableau columnWordcolumnWordToTableaustandardYoungTableauxcountStandardYoungTableauxsemiStandardYoungTableauxcountSemiStandardYoungTableauxTriunTriTriangularArraytriangularArrayUnsafefromTriangularArray kostkaContent_kostkaContentkostkaTableaux_kostkaTableauxcountKostkaTableaux SetPartition_standardizeSetPartitionfromSetPartitiontoSetPartitionUnsafetoSetPartition_isSetPartition setPartitionssetPartitionsWithKPartssetPartitionsNaivesetPartitionsWithKPartsNaivecountSetPartitionscountSetPartitionsWithKParts$fHasNumberOfPartsSetPartitionParen RightParen LeftParenBinTree'Leaf'Branch'BinTreeLeafBranchleafforgetNodeDecorations toRoseTree toRoseTree'parenthesesToStringstringToParenthesesforestToNestedParenthesesforestToBinaryTreenestedParenthesesToForestnestedParenthesesToForestUnsafenestedParenthesesToBinaryTree#nestedParenthesesToBinaryTreeUnsafebinaryTreeToNestedParenthesesbinaryTreeToForestnestedParenthesesrandomNestedParenthesesnthNestedParenthesescountNestedParenthesesfasc4A_algorithm_Pfasc4A_algorithm_Wfasc4A_algorithm_U binaryTreescountBinaryTreesbinaryTreesNaiverandomBinaryTreefasc4A_algorithm_RprintBinaryTree_drawBinaryTree_ LatticePathStepDownStepUpStep isValidPath isDyckPath pathHeight pathEndpointpathCoordinatespathNumberOfPeakspathNumberOfZeroTouchespathNumberOfTouches' dyckPathsdyckPathsNaivecountDyckPathsnestedParensToDyckPathdyckPathToNestedParensboundedDyckPathsboundedDyckPathsNaive latticePathslatticePathsNaivetouchingDyckPathstouchingDyckPathsNaivepeakingDyckPathspeakingDyckPathsNaivecountPeakingDyckPathsrandomDyckPath NonCrossing_isNonCrossing_isNonCrossingUnsafe_standardizeNonCrossingfromNonCrossingtoNonCrossingUnsafe toNonCrossingtoNonCrossingMaybesetPartitionToNonCrossingdyckPathToNonCrossingPartition#dyckPathToNonCrossingPartitionMaybenonCrossingPartitionToDyckPath$_nonCrossingPartitionToDyckPathMaybenonCrossingPartitionsnonCrossingPartitionsWithKPartscountNonCrossingPartitions$countNonCrossingPartitionsWithKPartsrandomNonCrossingPartition$fHasNumberOfPartsNonCrossingregularNaryTrees ternaryTreescountRegularNaryTreescountTernaryTreessemiRegularTreesprintTreeVertical_printTreeVerticalprintTreeVerticalLeavesOnlydrawTreeVertical_drawTreeVerticaldrawTreeVerticalLeavesOnly leftSpine rightSpine leftSpine_ rightSpine_leftSpineLengthrightSpineLengthclassifyTreeNode isTreeLeaf isTreeNode isTreeLeaf_ isTreeNode_treeNodeNumberOfChildrencountTreeNodescountTreeLeavescountTreeLabelsWithcountTreeNodesWithaddUniqueLabelsTreeaddUniqueLabelsForestaddUniqueLabelsTree_addUniqueLabelsForest_labelDepthTreelabelDepthForestlabelDepthTree_labelDepthForest_labelNChildrenTreelabelNChildrenForestlabelNChildrenTree_labelNChildrenForest_ derivTreesDot binTreeDot binTree'Dot forestDottreeDotWord GeneratorInvGenunGenshowGenshowWord inverseGen inverseWordallWords allWordsNoInvrandomGeneratorrandomGeneratorNoInv randomWordrandomWordNoInv multiplyFreereduceWordFreecountIdentityWordsFreecountWordReductionsFree multiplyZ2 multiplyZ3 multiplyZm reduceWordZ2 reduceWordZ3 reduceWordZmcountIdentityWordsZ2countWordReductionsZ2countIdentityWordsZ3NoInv$fFunctorGeneratorfind2kmpow'mulMod squareModpowModmakeChoiceFromIndices$fHasNumberOfPartsPartition#randomPermutationDurstenfeldSattoloReverseHoleTableauReverseTableauHolebinom2index'deIndex'toHolenextHolereverseTableau normalize normalize' startHole enumHoleshelper newLines'newLinessizes'$fIxTri parenToChar$fTraversableBinTree$fFoldableBinTree$fFunctorBinTreecontainers-0.5.5.1 Data.Tree subForest rootLabelNodeTreeForestbase Data.EitherLeftRight derivTrees'digraphBracket binTreeDot' binTree'Dot'