function key = i4_key_advance ( key )

%*****************************************************************************80
%
%% i4_key_advance() "advances" the key.
%
%  Discussion:
%
%    This routine implements one step of the recursion
%
%      key = ( 16807 * key ) mod ( 2^31 - 1 )
%
%    This version of the routine does not check whether the input value of
%    key is zero.  If the input value is zero, the output value will be zero.
%
%    If we repeatedly use the output of key_ADVANCE as the next input,
%    and we start with key = 12345, then the first few iterates are:
%
%         Input      Output
%          key        key
%
%         12345   207482415
%     207482415  1790989824
%    1790989824  2035175616
%    2035175616    77048696
%      77048696    24794531
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    05 April 2013
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Paul Bratley, Bennett Fox, Linus Schrage,
%    A Guide to Simulation,
%    Second Edition,
%    Springer, 1987,
%    ISBN: 0387964673,
%    LC: QA76.9.C65.B73.
%
%    Bennett Fox,
%    Algorithm 647:
%    Implementation and Relative Efficiency of Quasirandom
%    Sequence Generators,
%    ACM Transactions on Mathematical Software,
%    Volume 12, Number 4, December 1986, pages 362-376.
%
%    Pierre L'Ecuyer,
%    Random Number Generation,
%    in Handbook of Simulation,
%    edited by Jerry Banks,
%    Wiley, 1998,
%    ISBN: 0471134031,
%    LC: T57.62.H37.
%
%    Peter Lewis, Allen Goodman, James Miller,
%    A Pseudo-Random Number Generator for the System/360,
%    IBM Systems Journal,
%    Volume 8, Number 2, 1969, pages 136-143.
%
%  Input:
%
%    integer key, the key value.
%
%  Output:
%
%    integer key, the "next" key.
%
  i4_huge = 2147483647;

  key = floor ( key );

  key = mod ( key, i4_huge );

  if ( key < 0 )
    key = key + i4_huge;
  end

  k = floor ( key / 127773 );

  key = 16807 * ( key - k * 127773 ) - k * 2836;

  if ( key < 0 )
    key = key + i4_huge;
  end

  return
end
