Continued Fractions of Quadratic Irrationals

This program is an implementation of  the algorithm of theorem 11.4.1 to compute the continued fraction expansion of a quadratic irrational of the form   (A0 + Sqrt[n])/B0. The function takes four arguments, A0, B0, n and the number of terms of the expansion.  Here n must not be a perfect square, otherwise the method is incorrect and  you will   get a division by 0 error.   The second function prints the  specified number of terms of the continued fraction expansion of  Sqrt[n].  
 
  The programs can be modified to print  the pre-period and the periodic parts of the continued fractions.  For the expansion of  the square  root of n,  by  corollary 11.5.3, the period length  is the first k >1, such that B[k]=1.   You may wish to incorporate this into the program for the square root of n.  In addition, you should modify the program to print  any desired number of convergents of the continued fraction expansion.

CfracOfQuadratic[ A0_, B0_,n_,NumTerms_]:= 
              Module[{a,A,B,i,k,t},
                t= N[Sqrt[n]] ;
                A[0]=A0;
                B[0]=B0;
                a[0]=Floor[(A[0]+t)/B[0]];
                i=0;
                While[i<=NumTerms, 
                      A[i+1]=a[i]B[i]-A[i];
                      B[i+1]=(n-A[i+1]^2)/B[i];
                      a[i+1]=Floor[(A[i+1]+t)/B[i+1]];
                      i=i+1;];
                  Return[Table[a[k],{k,0,NumTerms}]]]

CfracOfRoot[n_,NumTerms_]:=CfracOfQuadratic[0,1,n,NumTerms];

CfracOfQuadratic[2,3,11,20]

CfracOfRoot[7,40]