1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
#!/bin/bash
# collatz.sh
# The notorious "hailstone" or Collatz series.
# -------------------------------------------
# 1) Get the integer "seed" from the command-line.
# 2) NUMBER <-- seed
# 3) Print NUMBER.
# 4) If NUMBER is even, divide by 2, or
# 5)+ if odd, multiply by 3 and add 1.
# 6) NUMBER <-- result
# 7) Loop back to step 3 (for specified number of iterations).
#
# The theory is that every such sequence,
#+ 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.
#
# This is an instance of an "iterate,"
#+ an operation that feeds its output back into its input.
# Sometimes the result is a "chaotic" series.
MAX_ITERATIONS=200
# For large seed numbers (>32000), try increasing MAX_ITERATIONS.
h=${1:-$$} # Seed.
# Use $PID as seed,
#+ if not specified as command-line arg.
echo
echo "C($h) -*- $MAX_ITERATIONS Iterations"
echo
for ((i=1; i<=MAX_ITERATIONS; i++))
do
# echo -n "$h "
# ^^^
# tab
# printf does it better ...
COLWIDTH=%7d
printf $COLWIDTH $h
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
# For more information on this strange mathematical function,
#+ see _Computers, Pattern, Chaos, and Beauty_, by Pickover, p. 185 ff.,
#+ as listed in the bibliography.
exit 0
|