Triangular Numbers
|
We can construct a program to find the terms of the triangular numbers series. Each term is the sum of first n natural (counting) numbers. These follow the arithmetic sequence 0, 1, 3, 6, 10, 15... where each term increases by the count value 1, 2, 3... We need 3 registers:
|
|
The operator resets all registers to 0 and the Input register to the n th term required. The train engine then begins its computational journey. It needs to carry out the following steps:
- Compare the Count with n (the n th term requested).
-
If the Count is equal to
n
, then Halt
- we're done, the sum will be showing in the Sum Register ...else... - Increment the Count register (ie increase by 1).
- Add the Count to the Sum register, producing the next triangular number.
- Loop back to the first step.
Note that we need to compare first in case we are asked for the 0 th term (or more likely forgot to set the input register). Also, all overflow errors from the Count Up or Adder are returned to the station. If C is greater than n then the train is returned as an error.
The 5 step program loop uses 3 different functions:
- Comparator function, to halt if C = n
- Count Up function, to increment C
- Accumulator function, to add C to S
|
| Click layout to pause/run train | Click points to switch 0/1 | Click start circle to reset train/points |
|
|
Lazy points switch between upper
0
or lower
1
branch lines
Trains arriving on a branch line switch the point to that line |
|
|
Sprung points allow branch line trains to join the main line
All main line trains go straight ahead and never 'branch off' |
How it works
The train will traverse the layout without intervention. Each return to the main program loop will yield the next triangular number in the lower sum Register S .
Eventually, when the Count equals the requested n th term, the comparator will return the train to the 'halt' siding. The n th triangular number can be read in the lower Sum S register.
Notes
This layout will produce an overflow error for the 6 th and 7 th terms. Increasing the register size by adding more stages will allow larger numbers to be computed. Each register can be extended indefinitely to the left. An S register with 8-stages would allow the 255 th triangular number of 32,640 to be computed.
Also see example Triangular Number layout with Clear & error line.