def collatz_len ( n ): #*****************************************************************************80 # ## collatz_len(): length of the Collatz sequence for a given starting point. # # Discussion: # # 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. # # Licensing: # # This code is distributed under the MIT license. # # Modified: # # 12 June 2022 # # Author: # # John Burkardt # # Input: # # integer n, the starting point for the sequence. # # Output: # # integer tlen: the length of the sequence. # if ( n <= 0 ): tlen = -1 return tlen tlen = 1 while ( n != 1 ): if ( ( n % 2 ) == 0 ): n = n // 2 else: n = 3 * n + 1 tlen = tlen + 1 return tlen def collatz_len_test ( ): print ( '' ) print ( 'collatz_len_test ( ):' ) print ( ' Return the length of a Collatz sequence' ) n = 7 tlen = collatz_len ( n ) print ( '' ) print ( ' Starting at ', n, ' the sequence has length ', tlen ) return if ( __name__ == "__main__" ): collatz_len_test ( )