#!/usr/bin/perl -w
#
# collatz_count.pl
#
#  Discussion:
#
#    collatz_count.pl 5
#
#    will compute the Collatz sequence that starts with 5, and 
#    print the number of terms in that sequence.
#
#    The Collatz sequence is defined recursively as follows:
#
#      Let T be the current entry of the sequence, and U the next:
#
#      If T = 1, the sequence terminates (or U = 1, your choice);
#      Else if T is even, U = T / 2;
#      Else (if T is odd, and greater than 1) U = 3 * T + 1.
#
#     N  Sequence                                                Length
#
#     1                                                               1
#     2   1                                                           2
#     3  10,  5, 16,  8,  4,  2,  1                                   8
#     4   2   1                                                       3
#     5  16,  8,  4,  2,  1                                           6
#     6   3, 10,  5, 16,  8,  4,  2,  1                               9
#     7  22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1   17
#     8   4,  2,  1                                                   4
#     9  28, 14,  7, ...                                             20
#    10   5, 16,  8,  4,  2,  1                                       7
#    11  34, 17, 52, 26, 13, 40, 20, 10,  5, 16, 8, 4, 2, 1          15
#    12   6,  3, 10,  5, 16,  8,  4,  2,  1                          10
#
#  Modified:
#
#    27 February 2006
#
#  Author:
#
#    John Burkardt
#
#  Reference:
#
#    Randal Schwartz, Tom Christiansen,
#    Learning Perl,
#    O'Reilly, 1997.
#
  if ( $#ARGV != 0 )
  {
    print "usage: collatz_count n\n";
    exit;
  }
  
  $n = int ( $ARGV[0] );
  $count = 1;
  
  while ( 1 < $n )
  {
    if ( $n % 2 == 0 )
    {
      $n = $n / 2;
    }
    else
    {
      $n = 3 * $n + 1;
    }
    $count = $count + 1;
  }
  printf ( "%d\n", $count );
