#! /usr/bin/env python3 # def collatz_inverse ( nlist ): #*****************************************************************************80 # ## collatz_inverse() returns the Collatz preimage of a list of integers. # # Licensing: # # This code is distributed under the MIT license. # # Modified: # # 28 January 2025 # # Author: # # John Burkardt # # Input: # # integer nlist[*]: a list of integers. # # Output: # # integer Tnlist[*]: the Collatz preimages of the values in nlist. # Tnlist = [] # # A even preimage of n is 2*n. # for n in nlist: Tnlist.append ( 2 * n ) # # Sometimes, there is an odd preimage of n. # for n in nlist: if ( n != 4 ): # We don't want the preimage of 4, which is 1 if ( n % 3 == 1 ): # Is n of the form 3*s+1? s = ( n - 1 ) // 3 # If so, solve n = 3*s+1 for s if ( s % 2 == 1 ): # If s is odd, it's a second preimage of n. Tnlist.append ( s ) # # Get the unique elements by turning the list into a set, # and then bringing it back as a list again. # Tnlist = list ( set ( Tnlist ) ) # # Sort the list. # Tnlist = sorted ( Tnlist ) return Tnlist def collatz_inverse_test ( ): #*****************************************************************************80 # ## collatz_inverse_test() tests collatz_inverse(). # # Licensing: # # This code is distributed under the MIT license. # # Modified: # # 10 October 2024 # # Author: # # John Burkardt # print ( '' ) print ( 'collatz_inverse_test():' ) print ( ' collatz_inverse() computes the preimage of a set of' ) print ( ' integers under the Collatz transformation.' ) for step in range ( 0, 13 ): if ( step == 0 ): nlist = [ 2 ] else: nlist = collatz_inverse ( nlist ) print ( nlist ) return if ( __name__ == "__main__" ): collatz_inverse_test ( )