2.7.64 Programming Tutorial Exercise 7

The trick here is to compute the harmonic numbers differently, so that the loop counter itself accumulates the sum of reciprocals. We use a separate variable to hold the integer counter.

1:  1          2:  1       1:  .
    .          1:  4
                   .

    1 t 1       1 RET 4      Z ( t 2 r 1 1 + s 1 & Z )

The body of the loop goes as follows: First save the harmonic sum so far in variable 2. Then delete it from the stack; the for loop itself will take care of remembering it for us. Next, recall the count from variable 1, add one to it, and feed its reciprocal to the for loop to use as the step value. The for loop will increase the “loop counter” by that amount and keep going until the loop counter exceeds 4.

2:  31                  3:  31
1:  3.99498713092       2:  3.99498713092
    .                   1:  4.02724519544
                            .

    r 1 r 2                 RET 31 & +

Thus we find that the 30th harmonic number is 3.99, and the 31st harmonic number is 4.02.