Exercise · Volume 1 · 1.2.8-3
Exercise 1.2.8-3
not stated yet in Lean solution written
| Rating | 25 |
|---|---|
| Kind | K6, write a program: write a MIX or MMIX program from the written solution |
| Section | Section 1.2.8 of Volume 1. Companion chapter: Fibonacci numbers |
The task
Write a program that prints the decimal values of 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: has 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 decimal digits. Use blocks of nine decimal digits ("limbs"), with base . A number is a list of limbs, the least significant first. The sum of two limbs and a carry is less than , so it fits in a machine word of bits or more. A number of digits has 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 and b holds at the top of the loop. The addition of the limbs is the school method with base . 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 is limb additions, and the whole table costs about 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 , to_text(limbs) equals str(F_n) computed by exact integer addition. The longest number has limbs, and the printed value of is . The first values printed are .
Remarks
Exercise 1.2.8-2 predicts the length of the output, and the program confirms it: the value has digits. On a machine with small words, such as MIX, a smaller base, for example or , 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.