function [ cycle_length, steps ] = middle_square_cycle_length ( seed, d )

%*****************************************************************************80
%
%% middle_square_next() computes the next middle square random value.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    18 June 2023
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Brian Hayes,
%    The Middle of the Square,
%    08 August 2022,
%    http://bit-player.org/
%
%  Input:
%
%    integer seed: the current seed, of no more than 2*D digits.
%
%    integer d: HALF the number of digits.  
%    Typical values are 2, 3, or 4.
%
%  Output:
%
%    integer cycle_length: the length of the cycle.
%
%    integer steps: the number of steps before the sequence cycled.
%
  verbose = false;

  store = zeros ( 10^(2*d) );
  steps = 0;
  value = seed;

  while ( true )

    steps = steps + 1;

    if ( store(value) ~= 0 )
      if ( verbose )
        fprintf ( 1, '\n' );
        fprintf ( 1, '  On step %d, sequence repeated the value %d\n', ...
          steps, value );
        fprintf ( 1, '  first encountered at step %d\n', store(value) );
      end
      cycle_length = steps - store(value);
      return
    else
      store(value) = steps;
      value = middle_square_next ( value, d );
    end

  end

  return
end
  
