2002-04-01 16:05:47 +00:00
|
|
|
#!/bin/bash
|
|
|
|
# collatz.sh
|
|
|
|
|
|
|
|
# The notorious "hailstone" or Collatz series.
|
|
|
|
# -------------------------------------------
|
2008-11-23 22:43:47 +00:00
|
|
|
# 1) Get the integer "seed" from the command-line.
|
|
|
|
# 2) NUMBER <-- seed
|
2002-04-01 16:05:47 +00:00
|
|
|
# 3) Print NUMBER.
|
|
|
|
# 4) If NUMBER is even, divide by 2, or
|
|
|
|
# 5)+ if odd, multiply by 3 and add 1.
|
2008-11-23 22:43:47 +00:00
|
|
|
# 6) NUMBER <-- result
|
2002-04-01 16:05:47 +00:00
|
|
|
# 7) Loop back to step 3 (for specified number of iterations).
|
|
|
|
#
|
2011-08-29 23:59:19 +00:00
|
|
|
# The theory is that every such sequence,
|
2002-04-01 16:05:47 +00:00
|
|
|
#+ no matter how large the initial value,
|
|
|
|
#+ eventually settles down to repeating "4,2,1..." cycles,
|
|
|
|
#+ even after fluctuating through a wide range of values.
|
|
|
|
#
|
2006-12-20 21:11:55 +00:00
|
|
|
# This is an instance of an "iterate,"
|
2008-11-23 22:43:47 +00:00
|
|
|
#+ an operation that feeds its output back into its input.
|
2002-04-01 16:05:47 +00:00
|
|
|
# Sometimes the result is a "chaotic" series.
|
|
|
|
|
|
|
|
|
|
|
|
MAX_ITERATIONS=200
|
2008-11-23 22:43:47 +00:00
|
|
|
# For large seed numbers (>32000), try increasing MAX_ITERATIONS.
|
2002-04-01 16:05:47 +00:00
|
|
|
|
2008-11-23 22:43:47 +00:00
|
|
|
h=${1:-$$} # Seed.
|
2002-07-22 15:11:51 +00:00
|
|
|
# Use $PID as seed,
|
|
|
|
#+ if not specified as command-line arg.
|
2002-04-01 16:05:47 +00:00
|
|
|
|
|
|
|
echo
|
2011-08-29 23:59:19 +00:00
|
|
|
echo "C($h) -*- $MAX_ITERATIONS Iterations"
|
2002-04-01 16:05:47 +00:00
|
|
|
echo
|
|
|
|
|
2014-07-05 13:38:40 +00:00
|
|
|
for ((i=1; i<=MAX_ITERATIONS; i++))
|
2002-04-01 16:05:47 +00:00
|
|
|
do
|
|
|
|
|
2008-11-23 22:43:47 +00:00
|
|
|
# echo -n "$h "
|
|
|
|
# ^^^
|
|
|
|
# tab
|
|
|
|
# printf does it better ...
|
|
|
|
COLWIDTH=%7d
|
|
|
|
printf $COLWIDTH $h
|
2002-04-01 16:05:47 +00:00
|
|
|
|
|
|
|
let "remainder = h % 2"
|
|
|
|
if [ "$remainder" -eq 0 ] # Even?
|
|
|
|
then
|
|
|
|
let "h /= 2" # Divide by 2.
|
|
|
|
else
|
|
|
|
let "h = h*3 + 1" # Multiply by 3 and add 1.
|
|
|
|
fi
|
|
|
|
|
|
|
|
|
|
|
|
COLUMNS=10 # Output 10 values per line.
|
|
|
|
let "line_break = i % $COLUMNS"
|
|
|
|
if [ "$line_break" -eq 0 ]
|
|
|
|
then
|
|
|
|
echo
|
|
|
|
fi
|
|
|
|
|
|
|
|
done
|
|
|
|
|
|
|
|
echo
|
|
|
|
|
2008-11-23 22:43:47 +00:00
|
|
|
# For more information on this strange mathematical function,
|
2006-12-20 21:11:55 +00:00
|
|
|
#+ see _Computers, Pattern, Chaos, and Beauty_, by Pickover, p. 185 ff.,
|
2002-04-01 16:05:47 +00:00
|
|
|
#+ as listed in the bibliography.
|
|
|
|
|
|
|
|
exit 0
|