function s = mollatz ( key )

%*****************************************************************************80
%
%% mollatz() computes the mollatz sequence for a given starting point.
%
%  Discussion:
%
%    The mollatz sequence is defined recursively as follows:
%
%      Let T be the current entry of the sequence, and U the next:
%
%      If T = repeats a previous value, the sequence terminates;
%      Else if T is even, U = T / 2;
%      Else (if T is odd, and greater than 1) U = 3 * T - 1.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    12 June 2022
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer key: the starting point for the sequence.
%    key must be positive.
%
%  Output:
%
%    integer S[*]: the mollatz sequence, starting with key.
%
  if ( key <= 0 )
    s = [];
    return
  end

  n = 1;
  t = key;
  s(n) = t;

  while ( true )

    if ( 2 * round ( t / 2 ) == t )
      t = t / 2;
    else
      t = 3 * t - 1;
    end

    n = n + 1;
    s(n) = t

    if ( any ( s(1:n-1) == t ) )
      break
    end

  end

  return
end
