home *** CD-ROM | disk | FTP | other *** search
- \ Lesson 5 Part 5 ( F-PC 3.5 Tutorial by Jack Brown )
-
- \ We are going to write a program using an indefinite loop that
- \ demonstrates the incredible integer property.
-
- \ Step 1: choose any integer larger than 2, call it n
- \ Step 2: if n is odd, replace n by 3n + 1 ; goto setp 4
- \ Step 3: if n is even, replace n by n/2
- \ Step 4: if n less than 2 goto step 5 otherwise goto step 2
- \ Step 5: stop.
-
- \ On reading the above algorithm you will soon discover that you cannot
- \ tell just how many loops will occur before you get to step 5. At first
- \ glance it appears that you would never get to step 5 and stop as half of
- \ the time, when n is odd, you are more than tripling n and the other half
- \ of the time when n is even you are just halfing n. To experiment with
- \ this algorithm we can use Forth indefinite loop structure to construct a
- \ program.
-
-
- \ Indefinite loop illustrates incredible integer property.
- : DOIT ( n -- )
- CR BEGIN DUP 2 MOD ( is n odd? )
- IF 3 * 1+ ( yes: tripple n and add 1 )
- ELSE 2/ ( no: half n )
- THEN
- #OUT @ 65 > ( check for end of line )
- IF CR THEN ( start new line if there )
- DUP 5 .R ( display current value of n )
- DUP 2 < ( continue until less than 2 )
- UNTIL DROP ;
-
-
-
-
-