%Solution for exercise 10: fakloesung.m
%Christoph Erath
function fakloesung

% factorial of k
k = 20;
% repeat n times for measuring very short execution times
n = 1000;

% iterative using for loop
tic
for i=1:n
  fak_for(k);
end
toc

% iterative using while loop
tic
for i=1:n
  fak_while(k);
end
toc

% iterative without any loop
tic
for i=1:n
  fak_noloop(k);
end
toc

% recursive  
tic
for i=1:n
  fak_rek(k);
end
toc

% MATLAB internal function
tic
for i=1:n
  factorial(k);
end
toc


% ------------------------------------------------------------------------------
% iterative using for loop
% ------------------------------------------------------------------------------
function fakN = fak_for(n)
  fakN = 1;
  for k=1:n
    fakN = fakN*k;
  end

% ------------------------------------------------------------------------------
% iterative using while loop
% ------------------------------------------------------------------------------
function fakN = fak_while(n)
  fakN = 1;
  k = 1;
  while (k<=n)
    fakN = fakN*k;
    k = k + 1;
  end

% ------------------------------------------------------------------------------
% iterative without any loop
% ------------------------------------------------------------------------------
function fakN = fak_noloop(n)
  fakN = prod(1:n);
  
% ------------------------------------------------------------------------------
% recursive  
% ------------------------------------------------------------------------------
function fakN = fak_rek(n)
  if n==1
    fakN = 1;
  else
    fakN = n*fak_rek(n-1);
  end

