title: How to calculate big combinatorics amount in tsql
body: <p>In sql2014 I have a table with 4 integers (W,X,Y,Z) and a bigint B.
  B = C(X,Z)*C(W-X;Y-Z) where C(n,k) stands for combinations of k objects taken from n objects , that is, the usual n!/[k!(n-k)!]</p>
  
  <p>The highest value of W,X,Y and Z is 40 so that the biggest B is 1.37847E+11
  I can calculate the correct values using Excel (using the function COMBIN) but I can't to the same in SQL. I can generate the table with all the combinations of W,X,Y,Z that i need but when I try to calculate B for big values I don't know how to treat things like "40!".</p>
  
  <p>I would like to use a CTE with preinserted values of factorial, something like:</p>
  
  <pre><code>;WITH factorials AS(
  SELECT 2 as N, 2 AS F
  UNION ALL
  SELECT 3,6
  UNION ALL...
  )
  </code></pre>
  
  <p>but i dont know how to store 40! and the like.</p>
  
  <p>Using .NET to fill the table is not an option, it should be made by SQL.</p>
  
  <p>I even thought of using a table like the CTE before and storing the factorial in two or three columns, the first storing billions, the second storing billions of billions and so on (using INTs) but then I don't know how to make divisions among numbers stored like this, as in (Ax10^9+B)/(Cx10^9+D). </p>
  
  <p>How do I manage integers larger than bigint in tsql?</p>