2021-01-15 MATH 3600 3n+1 problem

325 days ago by calkin

The $3n+1$ problem, aka the Collatz conjecture, the Hailstone conjecture, the Ulam problem, etc.

Define $f(n)$ recursively by $f(n)=n/2$ if $n$ is even, and $f(n)= 3n+1$ if $n$ is odd.

Start at a number $n_0$.  Compute $f(n_0), f(f(n_0)), f(f(f(n_0)))$ etc.

def f(n): if n.is_integer() and n>0: if n==1: return(0) elif is_odd(n): return(3*n+1) else: return(n/2) else: return("Please enter a positive integer!") 
       
type(f(4)) 
       
<type 'sage.rings.rational.Rational'>
<type 'sage.rings.rational.Rational'>
f(5) 
       
16
16
f(f(4)) 
       
1
1
f(-1) 
       
'Please enter a positive integer!'
'Please enter a positive integer!'
is_odd(1/2) 
       
Traceback (click to the left of this block for traceback)
...
ZeroDivisionError: Inverse does not exist.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "_sage_input_13.py", line 10, in <module>
    exec compile(u'open("___code___.py","w").write("# -*- coding: utf-8 -*-\\n" + _support_.preparse_worksheet_cell(base64.b64decode("aXNfb2RkKDEvMik="),globals())+"\\n"); execfile(os.path.abspath("___code___.py"))
  File "", line 1, in <module>
    
  File "/tmp/tmpUIwqfN/___code___.py", line 3, in <module>
    exec compile(u'is_odd(_sage_const_1 /_sage_const_2 )
  File "", line 1, in <module>
    
  File "/usr/local/sage-6.10/local/lib/python2.7/site-packages/sage/misc/functional.py", line 792, in is_odd
    return not is_even(x)
  File "/usr/local/sage-6.10/local/lib/python2.7/site-packages/sage/misc/functional.py", line 745, in is_even
    except AttributeError: return x%2==0
  File "sage/rings/rational.pyx", line 2531, in sage.rings.rational.Rational.__mod__ (/usr/local/sage-6.10/src/build/cythonized/sage/rings/rational.c:22684)
  File "sage/rings/integer.pyx", line 6097, in sage.rings.integer.Integer.inverse_mod (/usr/local/sage-6.10/src/build/cythonized/sage/rings/integer.c:38023)
ZeroDivisionError: Inverse does not exist.
 
       
n.is_integer() 
       
True
True
       
5
5
hailstone=[[1,0]] champions=[] max_value_seen=3 for i in srange(2,10001): stepcounter=0 n=i while n> 1: n=f(n) stepcounter+=1 if stepcounter> max_value_seen: max_value_seen = stepcounter champions.append([i,max_value_seen]) hailstone.append([i,stepcounter]) 
       
list_plot(hailstone[3:100000]) 
       
list_plot(champions)