Next: , Previous: , Up: Answers to Exercises   [Contents][Index]

2.7.27 List Tutorial Exercise 9

Step one is to convert our integer into vector notation.

1:  25129925999           3:  25129925999
    .                     2:  10
                          1:  [11, 10, 9, ..., 1, 0]
                              .

    25129925999 RET           10 RET 12 RET v x 12 RET -

1:  25129925999              1:  [0, 2, 25, 251, 2512, ... ]
2:  [100000000000, ... ]         .
    .

    V M ^   s 1                  V M \

(Recall, the \ command computes an integer quotient.)

1:  [0, 2, 5, 1, 2, 9, 9, 2, 5, 9, 9, 9]
    .

    10 V M %   s 2

Next we must increment this number. This involves adding one to the last digit, plus handling carries. There is a carry to the left out of a digit if that digit is a nine and all the digits to the right of it are nines.

1:  [0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1]   1:  [1, 1, 1, 0, 0, 1, ... ]
    .                                          .

    9 V M a =                                  v v

1:  [1, 1, 1, 0, 0, 0, ... ]   1:  [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]
    .                              .

    V U *                          v v 1 |

Accumulating * across a vector of ones and zeros will preserve only the initial run of ones. These are the carries into all digits except the rightmost digit. Concatenating a one on the right takes care of aligning the carries properly, and also adding one to the rightmost digit.

2:  [0, 0, 0, 0, ... ]     1:  [0, 0, 2, 5, 1, 2, 9, 9, 2, 6, 0, 0, 0]
1:  [0, 0, 2, 5, ... ]         .
    .

    0 r 2 |                    V M +  10 V M %

Here we have concatenated 0 to the left of the original number; this takes care of shifting the carries by one with respect to the digits that generated them.

Finally, we must convert this list back into an integer.

3:  [0, 0, 2, 5, ... ]        2:  [0, 0, 2, 5, ... ]
2:  1000000000000             1:  [1000000000000, 100000000000, ... ]
1:  [100000000000, ... ]          .
    .

    10 RET 12 ^  r 1              |

1:  [0, 0, 20000000000, 5000000000, ... ]    1:  25129926000
    .                                            .

    V M *                                        V R +

Another way to do this final step would be to reduce the formula ‘10 $$ + $ across the vector of digits.

1:  [0, 0, 2, 5, ... ]        1:  25129926000
    .                             .

                                  V R ' 10 $$ + $ RET

Next: List Tutorial Exercise 10, Previous: List Tutorial Exercise 8, Up: Answers to Exercises   [Contents][Index]