% derangement_keep2.m
%  Evaluate the derangement sequence using a two-step stepping stone.
%
n = input ( 'Enter the element index: ' );

for i = 0 : n

  if ( i == 0 )
    d = 1;
  elseif ( i == 1 )
    dold = d;
    d = 0;
  else
    doldest = dold;
    dold = d;
    d = ( i - 1 ) * ( dold + doldest );
  end

  fprintf ( 'D(%d) = %d\n', i, d );

end

