# A simple sequential program illustrating the "3n+1" problem, # called "wondrous numbers" in Hofstadter's "Godel Escher Bach". # # usage: a.out n to trace the integer n # a.out m n to trace all integers from m to n # default: a.out 2 25 # # Given a positive integer n, halve it if even, or replace by 3n+1 # if odd. Stop at 1. The sequences are interesting, and nobody has # proved that all initial values lead to termination. # # Try "a.out 27". # # For full details see Jeffrey Lagarias, The 3x+1 Problem and # Generalizations, American Mathematical Monthly, vol.92 no.1 # (January, 1986), pp. 3-25. resource wondrous() var lwb: int := 2 # lower bound defaults to 2 var upb: int := 25 # upper bound defaults to 25 var n: int # n is the working value if getarg(1, lwb) = 1 -> # if one argument set as lower, upper bounds upb := lwb fi getarg(2, upb) # reset upper bound to 2nd argument if given fa i := lwb to upb -> # for each integer in selected range: writes(i, ":") # print it n := i do n > 1 -> # iterate until we hit 1 if n % 2 = 1 -> n := 3*n+1 # 3n+1 if odd [] else -> n := n/2 # n/2 if even fi writes(" ", n) # write new value od write() # terminate line at end of sequence af end wondrous /* ............... Example compile and run(s) % sr -o wondrous wondrous.sr % ./wondrous 2: 1 3: 10 5 16 8 4 2 1 4: 2 1 5: 16 8 4 2 1 6: 3 10 5 16 8 4 2 1 7: 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 8: 4 2 1 9: 28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 10: 5 16 8 4 2 1 11: 34 17 52 26 13 40 20 10 5 16 8 4 2 1 12: 6 3 10 5 16 8 4 2 1 13: 40 20 10 5 16 8 4 2 1 14: 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 15: 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1 16: 8 4 2 1 17: 52 26 13 40 20 10 5 16 8 4 2 1 18: 9 28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 19: 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 20: 10 5 16 8 4 2 1 21: 64 32 16 8 4 2 1 22: 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 23: 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1 24: 12 6 3 10 5 16 8 4 2 1 25: 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 % ./wondrous 27 27: 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1 % ./wondrous 29 30 29: 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 30: 15 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1 */