#! /usr/bin/env python3 # def collatz_test ( ): #*****************************************************************************80 # ## collatz_test() # import json # # Create the dict. # collatz_dict = {} # # Store data for 1 <= n < 21. # n_max = 21 collatz_dict_initialize ( collatz_dict, n_max ) print ( '' ) print ( ' After initialization with n_max = ', n_max, 'the Collatz dict' ) print ( ' has "length" (number of entries) = ', len ( collatz_dict ) ) # # Now add data for n = 27. # n = 27 collatz_add_to_dict ( collatz_dict, n ) print ( '' ) print ( ' After adding data for n = ', n, 'the Collatz dict' ) print ( ' has "length" (number of entries) = ', len ( collatz_dict ) ) # # Now write dict to JSON file. # filename = 'collatz_dict.json' output = open ( filename, 'w' ) json.dump ( collatz_dict, output ) output.close ( ) print ( '' ) print ( ' collatz_dict was written to "' + filename + '"' ) return def collatz_dict_initialize ( collatz_dict, n_max ): #*****************************************************************************80 # ## collatz_dict_initialize() # for n in range ( 1, n_max ): collatz_add_to_dict ( collatz_dict, n ) return def collatz_add_to_dict ( collatz_dict, n ): #*****************************************************************************80 # ## collatz_add_to_dict() # while ( not ( n in collatz_dict ) ): n2 = collatz ( n ) collatz_dict[n] = n2 n = n2 return def collatz ( n ): #*****************************************************************************80 # ## collatz() applies one step of the Collatz iteration to an integer. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 11 June 2022 # # Author: # # John Burkardt # # Input: # # integer n: the starting value. # # Output: # # integer n2: the transformed value. # if ( not isinstance ( n, int ) ): raise Exception ( 'collatz: type(n) = ', type ( n ), \ ', but n must be an integer.' ) elif ( n < 1 ): raise Exception ( 'collatz: n =', n, ', but 1 <= n required.' ) elif ( n == 1 ): n2 = 1 elif ( ( n % 2 ) == 0 ): n2 = n // 2 else: n2 = 3 * n + 1 return n2 if ( __name__ == '__main__' ): collatz_test ( )