    'http://rosettacode.org/wiki/Pi#Pascal
    'http://www.pi314.net/eng/goutte.php
     
    /* A spigot algorithm for the digits of pi, 
       Stanley Rabinowitz and Stan Wagon
    */
     
    uses console
     
    function Pi_Spigot(int n) as string
       int  count, j, k, q, nines, predigit
       int x,i
       int idx
     
       count = 10*n \ 3
     
       'Create dynamic array
       sys aa=getmemory count * sizeof(uint)
       uint a at aa
     
       string s = stringbytes(n,0)  'nuls   
       byte ss at strptr s
     
       for j = 1 to count 
          a[j] = 2                  'Start with 2s
       next j
       nines = 0
       predigit = 0                 'First predigit is a 0
     
       for j = 1 to n
          if mod(j,1000) = 0 then print j & cr   
        
          'Only calculate as far as needed 
          '+16 for security digits ~5 decimals
          i = (n-j)*10 \ 3 +16
          if i > count then i = count
          q = 0
          do                        'Work backwards
             x  = 10*a[i] + q*i
             q = x \ (2*i - 1)
             a[i] = x - q*(2*i - 1) 'mod(x,2*i - 1)
             i--
             if i<= 0 then exit do
          end do
     
          a[1] = mod(q,10)
          q = q \ 10    
          if q = 9 then
            nines += 1
          else
            if q = 10 then
              idx++ : ss[idx]=predigit+1
              for k = 1 to nines : idx++ : ss[idx]=0 : next k   'zeros
              predigit = 0
              nines = 0
            else      
              if j > 1 then idx++ : ss[idx]=predigit
              predigit = q
              if nines <> 0 then
                for k = 1 to nines : idx++ : ss[idx]=9 : next k 'nine
                nines = 0
              end if
            end if
          end if
       next j
       '
       idx++ : ss[idx]=predigit 'final predigit
       if nines then 'remaining nines
         for k = 1 to nines
           idx++ : ss[idx]=9
         next k
         nines = 0
       end if
       'convert to ascii
       for x=1 to n : ss[x]+=48 : next x
     
       'release dynamic array
       freememory aa
     
       return s
    end function
     
    cls
    print "This will calculate pi and save the result as a text file"
    printl "How many digits? "
    int num=val(rtrim ltrim input())
     
    string s=Pi_Spigot(num)
    print s
     
    putfile("pi.txt",s)  
     
    printl
    printl "Saved as pi.txt"
    printl "Enter ... " : waitkey
     