taocp

This site has no text of the book. Keep your own copy of TAOCP next to it. See what is checked.

Exercise · Volume 1 · 1.2.8-3

Exercise 1.2.8-3

not stated yet in Lean solution written

Rating25
KindK6, write a program: write a MIX or MMIX program from the written solution
SectionSection 1.2.8 of Volume 1. Companion chapter: Fibonacci numbers

The task

Write a program that prints the decimal values of F1,F2,…,F1000F_1, F_2, \ldots, F_{1000} with exact arithmetic on long numbers.

The exact wording is in your copy of the book.

Hints

Open one hint at a time. Try the exercise again after each.

Hint 1

Exercise 1.2.8-2 gives the size: F1000F_{1000} has 209209 digits, which is too large for one machine word. Store each number as an array of small blocks of digits.

Hint 2

Keep two arrays for two consecutive numbers. One step of the loop adds them block by block from the low end, with a carry, and then shifts the roles of the arrays.

Hint 3

Print the top block as it is and every lower block with leading zeros, so that each block shows exactly the same number of digits.

Solution

Show the solution

The numbers have at most 209209 decimal digits. Use blocks of nine decimal digits ("limbs"), with base B=109B = 10^9. A number is a list of limbs, the least significant first. The sum of two limbs and a carry is less than 2B2B, so it fits in a machine word of 3131 bits or more. A number of 209209 digits has 2424 limbs.

BASE = 10**9

def fibonacci_table(count):
    a = [0]          # F(0)
    b = [1]          # F(1)
    for n in range(1, count + 1):
        yield n, b
        carry = 0
        c = []
        for i in range(max(len(a), len(b))):
            s = carry + (a[i] if i < len(a) else 0) + (b[i] if i < len(b) else 0)
            c.append(s % BASE)
            carry = s // BASE
        if carry:
            c.append(carry)
        a, b = b, c

def to_text(limbs):
    return str(limbs[-1]) + "".join(f"{x:09d}" for x in reversed(limbs[:-1]))

for n, limbs in fibonacci_table(1000):
    print(n, to_text(limbs))

The loop keeps the invariant that a holds Fn−1F_{n-1} and b holds FnF_n at the top of the loop. The addition of the limbs is the school method with base BB. The top limb has no leading zeros, because the addition adds a new top limb only when the carry is not zero. The cost for FnF_n is O(n)O(n) limb additions, and the whole table costs about 24⋅100024 \cdot 1000 limb additions at most.

For a machine with small words, such as MIX, take the same plan with a limb of fewer digits and a word array. The structure of the loop does not change.

Check

Run the program and compare with the integers of python3: for each n≤1000n \le 1000, to_text(limbs) equals str(F_n) computed by exact integer addition. The longest number has 2424 limbs, and the printed value of F100F_{100} is 354224848179261915075354224848179261915075. The first values printed are 1,1,2,3,5,8,131, 1, 2, 3, 5, 8, 13.

Remarks

Exercise 1.2.8-2 predicts the length of the output, and the program confirms it: the value F1000F_{1000} has 209209 digits. On a machine with small words, such as MIX, a smaller base, for example 10410^4 or 10510^5, keeps the sum of two limbs and a carry inside one word.

This solution is checked, and a person has not reviewed it yet. The source.

In Lean

not stated yet The exercise is not stated in Lean yet.

The status is computed from the Lean build. The node of the map.

Something is wrong? Report it.