title: Calculate Nth Pi Digit
body: <p>I am trying to calculate the nth digit of Pi without using <code>Math.Pi</code> which can be specified as a parameter.
  I modified an existing algorithm, since I like to find the Nth digit without using string conversions or default classes.
  This is how my algorithm currently looks like:</p>
  
  <pre><code>   static int CalculatePi(int pos)
      {
          List&lt;int&gt; result = new List&lt;int&gt;();
          int digits = 102;
          int[] x = new int[digits * 3 + 2];
          int[] r = new int[digits * 3 + 2];
          for (int j = 0; j &lt; x.Length; j++)
              x[j] = 20;
          for (int i = 0; i &lt; digits; i++)
          {
              int carry = 0;
              for (int j = 0; j &lt; x.Length; j++)
              {
                  int num = (int)(x.Length - j - 1);
                  int dem = num * 2 + 1;
                  x[j] += carry;
                  int q = x[j] / dem;
                  r[j] = x[j] % dem;
                  carry = q * num;
              }
              if (i &lt; digits - 1)
  
                  result.Add((int)(x[x.Length - 1] / 10));
              r[x.Length - 1] = x[x.Length - 1] % 10; ;
              for (int j = 0; j &lt; x.Length; j++)
                  x[j] = r[j] * 10;
          }
          return result[pos];
      }
  </code></pre>
  
  <p>So far its working till digit 32, and then, an error occurs.
  When I try to print the digits like so:</p>
  
  <pre><code>  static void Main(string[] args)
      {
          for (int i = 0; i &lt; 100; i++)
          {
              Console.WriteLine("{0} digit of Pi is : {1}", i, CalculatePi(i));
          }
  
          Console.ReadKey();
      }
  </code></pre>
  
  <p>This I get 10 for the 32rd digit and the 85rd digit and some others as well, which is obviously incorrect.</p>
  
  <p><img src="https://puu.sh/i7eDd/04c298b651.png" alt="enter image description here"></p>
  
  <p>The original digits from 27 look like so:</p>
  
  <p><strong>...3279502884.....</strong></p>
  
  <p>but I get</p>
  
  <p><strong>...32794102884....</strong></p>
  
  <p>Whats wrong with the algorithm, how can I fix this problem?
  And can the algorithm still be tweaked to improve the speed?</p>