--------PASCAL-------------
var A, B : array[0..3999] of integer;
    i,j,k,l,m : integer;

begin
  for i:=0 to 3999 do begin
    A[i] := 0;  B[i] := 0;
  end;
  k := -1; m := 0;
  while (A[1000]=0) do begin
    A[0] := A[0] + 1; B[0] := B[0] + 1;
    for j:=0 to 3998 do begin
      B[j+1] := B[j+1] + B[j] div 13;
      B[j] := B[j] mod 13;
    end;
    l := -1;
    for j:=0 to 3998 do begin
      if (A[j]>0) and (k<j) then begin
        k:=j; l:=j;
      end;
      A[j+1] := A[j+1] + (A[j] div (j+2)); 
      A[j] := A[j] mod (j+2);
    end;
    if l>-1 then m := m+B[0];
  end;
end.

----------C----------------
#include <stdio.h>

int A[4000], B[4000];
int i,j,k,l,m;

int main(void) {
  for (i=0;i<4000;i++) { A[i]=B[i]=0; } k=-1; m=0;
  while (!A[1000]) {
    A[0]++; B[0]++;
    for (j=0;j<3999;j++) { B[j+1]+=B[j]/13; B[j]%=13; }
    for (j=0,l=-1;j<3999;j++) { 
      if ((A[j]>0) && (k<j)) { k=l=j; }
      A[j+1]+=A[j]/(j+2); A[j]%=(j+2); 
    }
    if (l>-1) m+=B[0];
  }
  printf("%d\n",m);
  return 0;
}
