%**************************************************************************
%*     Problem 1.2                                                        *
%*                                                                        *
%*     This program evaluates factrial n! using the Stiring formula       *
%*     and compares it with the exact valuefor n=10, 100, 1000 and 10000. *
%*     More specifically, we evaluate the following ratio                 *
%*                                                                        *
%*          approximated n!                                               *
%*     R = ------------------                                             *
%*             exact n!                                                   *
%*                                                                        *
%*     Programed by Ryoichi Kawai for Computational Physics Course.       *
%*     Last modification:  01/11/2019.                                    *
%**************************************************************************

% set the smallest n
n=10;

% set the largest n
nmax=10000;

while (n<nmax+1)  % repeat the following block until n=nmax
   
   % evaluate log(n!) using the Stiring approximation
   stiring = n*log(n) - n + 0.5*log(2*pi*n);  
   
   % evauate the exact exact log(n!)
   exact = sum(log(1:n));
   
   % log(approx n!/exact n!) = log(approx n!) - log(exact n!)  
   logR = stiring - exact;
    
   % R = exp(log R)    
   R=exp(logR);
   
   
   % print out the result
    fprintf('n= %8d, R= %20.15e\n',n,R)
    
    % increment n by factor 10
    n=n*10;
    
end % end of the while block
