Skip to content

Fibonacci with a memory

planning ahead

Level 1 of 3

Also called Memoisation and Top-down dynamic programming.

how it works

The idea on F(5), then the whole method on F(6), as the watch page runs it.

The Fibonacci numbers start 0, 1, and each later one is the two before it added up: 0, 1, 1, 2, 3, 5, 8. Call them F(0), F(1), F(2) and on, so F(6) is 8. The plain method follows that rule. To work out F(6), it asks for F(5), then F(4), and each of those asks for two more. F(1) and F(0) ask for nothing. It is right, and wasteful: it works the same numbers out again and again. So keep a memo, a list of the answers so far, which the watch page calls the memory. Each time you ask for a number, look in the memo first. If it is there, that is the answer, and you ask for nothing more. If not, work it out and write it in. This page counts calls, one each time a number is asked for, the first included. Sections 2, 3 and 5 name them times asked. A call that has begun and not ended is waiting, and the newest is the one running. The code below, in the language Python, does the same.

15 calls, 6 different problems543210121032101
  • first time
  • asked before
The plain method on F(5). Each circle is one call, holding the number it asks for, joined to the call that asked. It runs from the left, so the left-hand 3 comes first, and the other 3 repeats it.
9 calls: 6 worked out, 3 answered at once543210123
  • first time
  • asked before, answered at once
The same with a memo. A repeat asks for nothing more, so the 6 calls under the repeats go, and 15 calls become 9.
numberasked, plainasked, with a memo
F(5)11
F(4)11
F(3)22
F(2)32
F(1)52
F(0)31
How often the two drawings above ask for each number, 15 calls and 9. The repeats pile up at the bottom. With a memo, no number is asked for more than twice.
F(6): 8 moments of its 19 steps, the steps between them left for the watch page
  1. step 1 of 19

    0123456FF6

    Ask for F(6). The memory is empty, so it has to be worked out.

    what it remembers to know where it is
    working on
    6
    answer
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  2. step 6 of 19

    0123456FF6F5F4F3F2F1

    To work out F(2), first ask for F(1). It is not in the memory yet.

    what it remembers to know where it is
    working on
    1
    answer
    not yet

    Where it says not yet, nothing is held there at that moment.

    watch from here

  3. step 7 of 19

    0123456F1F6F5F4F3F2

    F(1) is 1 by the rule, so write 1 in the memory.

    what it remembers to know where it is
    working on
    1
    answer
    1

    watch from here

  4. step 9 of 19

    0123456F01F6F5F4F3F2

    F(0) is 0 by the rule, so write 0 in the memory.

    what it remembers to know where it is
    working on
    0
    answer
    0

    watch from here

  5. step 10 of 19

    0123456F011F6F5F4F3

    F(2) is 1 + 0 = 1. Write it in the memory.

    what it remembers to know where it is
    working on
    2
    answer
    1

    watch from here

  6. step 11 of 19

    0123456F011F6F5F4F3

    F(1) is in the memory already: 1. No need to work it out again.

    what it remembers to know where it is
    working on
    1
    answer
    1

    watch from here

  7. step 12 of 19

    0123456F0112F6F5F4

    F(3) is 1 + 1 = 2. Write it in the memory.

    what it remembers to know where it is
    working on
    3
    answer
    2

    watch from here

  8. step 19 of 19

    0123456F0112358

    Done: F(6) is 8.

    what it remembers to know where it is
    working on
    not yet
    answer
    8

    Where it says not yet, nothing is held there at that moment.

    watch from here

the steps, in plain words
  1. ask for F(k): if the memory has it, the answer is therePython lines 9, 10 and 11
  2. if k is 0 or 1, F(k) is k, so write it in the memoryPython lines 12, 13 and 18
  3. otherwise ask for F(k - 1), then for F(k - 2)Python lines 14, 15 and 16
  4. add the two answers, and write F(k) in the memoryPython lines 17 and 18
  5. F(n) is the answerPython line 21
the same in Python

The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.

def fibonacci_memo(n):
    """Work out F(n), writing each answer down the first time.

    F(0) is 0, F(1) is 1, and every later number is the two before it added up.
    n is a whole number from 0. Returns F(n).
    """
    memo = {}  # the answers worked out so far, by k

    def ask(k):
        if k in memo:  # in the memo already, so that is the answer
            return memo[k]
        if k < 2:  # F(0) is 0 and F(1) is 1
            answer = k
        else:
            first = ask(k - 1)  # ask for F(k - 1), then for F(k - 2)
            second = ask(k - 2)
            answer = first + second  # add the two answers
        memo[k] = answer  # write it in the memo
        return answer

    return ask(n)

how it scales

The plot counts the calls the method makes on F(n), measured from 10 to 100,000.

Each mark across or up is ten times the one before. The line climbs one mark up for each mark across: 199 calls at 100 and 1,999 at 1,000, about 10 times. Here the cost is the calls, and a slope of 1 means it grows as nn, as section 4's question 1 derives. The plain method is not on this plot: at 100 it would make about 1,146 billion billion calls.

times asked, ten times more at each mark up

slope 1102104106108101102103104105106107slope 1101102103104105106107108101102103104105106107slope 1101102103104105106107108101102103104105106107

nn, the number asked for, ten times more at each mark to the right

  • asking for F(n), the one run there is for that nnsolid where measured by running it; dashed where its formula carries it on to ten millionslope 1: ten times n, 10 times the work
how long the calls on F(n) take, at a billion a second
nntimes askedtime
1,0001,999about 2 microseconds
100,000199,999about 200 microseconds
10,000,00019,999,999about 20 milliseconds

The times asked are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.

make these counts yourself

Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.

"""Count Fibonacci with a memo's calls yourself, as the plot on this page does.

Run it with Python 3.12 or later. For each n it prints the calls the method
makes and how many of them the memo answers, up to n = 100,000, and the plain
method's calls up to n = 30, where they are still quick to run. The counts are
the same on any computer; only the time differs.
"""

import sys

sys.setrecursionlimit(200_000)  # at n = 100,000, 100,000 calls wait, one on another


def fibonacci_memo(n):
    """Work out F(n), writing each answer down the first time.

    F(0) is 0, F(1) is 1, and every later number is the two before it added up.
    n is a whole number from 0. Returns F(n).
    """
    memo = {}  # the answers worked out so far, by k

    def ask(k):
        if k in memo:  # in the memo already, so that is the answer
            return memo[k]
        if k < 2:  # F(0) is 0 and F(1) is 1
            answer = k
        else:
            first = ask(k - 1)  # ask for F(k - 1), then for F(k - 2)
            second = ask(k - 2)
            answer = first + second  # add the two answers
        memo[k] = answer  # write it in the memo
        return answer

    return ask(n)


def counts(n):
    """The same method on n, counting its calls and those the memo answers.

    It keeps only which numbers are written, as the calls do not depend on the
    numbers, and at n = 100,000 they would fill a lot of memory.
    """
    written = set()
    calls = 0
    answered = 0

    def ask(k):
        nonlocal calls, answered
        calls += 1
        if k in written:
            answered += 1
            return
        if k >= 2:
            ask(k - 1)
            ask(k - 2)
        written.add(k)

    ask(n)
    return calls, answered


def count(n):
    """How many calls the method makes on n."""
    return counts(n)[0]


def plain_calls(n):
    """The plain method on n, with no memo, counting its calls."""
    calls = 0

    def ask(k):
        nonlocal calls
        calls += 1
        if k < 2:
            return k
        return ask(k - 1) + ask(k - 2)

    ask(n)
    return calls


if __name__ == "__main__":
    print(f"{'n':>6} {'calls':>7} {'answered':>9}")
    for n in (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10_000, 20_000, 50_000, 100_000):
        calls, answered = counts(n)
        print(f"{n:>6} {calls:>7} {answered:>9}")
    print()
    print(f"{'n':>6} {'plain calls':>12} {'with a memo':>12}")
    for n in (5, 10, 20, 30):
        print(f"{n:>6} {plain_calls(n):>12} {count(n):>12}")

best, worst and average

Best, worst and average usually name different inputs of one size. Here the size is the number you ask for, so each nn is one input and one run, the same every time. So the table has one column, under the name worst, and no average is worked out.

A case is one kind of input. Here each nn is one input, so there is one case. A bound says how fast its cost grows as nn grows.

The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
worstasking for F(n), the one run there is for that nn
times asked2n−12n - 1, from 1 up
answered from the memoryn−2n - 2, from 2 up
how the times asked grow in each case
tight, Θ\ThetaΘ(n)\Theta(n)
ceiling, OOO(n)O(n)
floor, Ω\OmegaΩ(n)\Omega(n)

extra memory: From 2 up, a memo of n+1n + 1 numbers, and at most nn calls waiting.

Extra memory is the room it needs on top of the input itself, while it runs.

nF(n)callsworked outansweredmost waiting
001101
111101
213302
325413
437524
559635
6811746
Counted by the run. Calls are worked out plus answered. In the table above, 2n−12n - 1 holds from 1 up. At 0 it gives less than 0, and F(0) makes 1 call. n−2n - 2 holds from 2 up. Below that it gives less than 0, and no call is answered.

where the formula comes from

Seven questions, each worked line by line. Question 1 is the count the plot draws.

Question 1: how many calls, CC, does the method make on nn, from 1 up?
  1. the move: count who asks

    the line:
    C=1+2(n−1)C = 1 + 2(n - 1)
    7 calls: 5 worked out, 2 answered at once4321012
    • first time
    • asked before, answered at once
    F(4) with a memo, 7 calls. The solid 4, 3 and 2 each ask for 2. The rest ask for nothing.

    why it is allowed: The first call counts 1. Every other call is asked for by a call working its number out. F(2) up to F(n) are each worked out once, which is n−1n - 1 numbers, and each asks for 2. F(1) and F(0) ask for nothing, and nor does a call the memo answers. For 4, 1 + 2 times 3, which is 7.

  2. the move: multiply out

    the line:
    C=1+2n−2C = 1 + 2n - 2

    why it is allowed: 2 lots of n−1n - 1 is 2 lots of nn, less 2. For 4, 1 + 8 - 2.

  3. the move: add them up

    the line:
    C=2n−1C = 2n - 1

    why it is allowed: 1 less 2 leaves less 1. For 4, 7.

  4. the move: a ceiling

    the line:
    C≤2nC \le 2n

    why it is allowed: Taking 1 away leaves less. For 4, CC is 7, at most 8.

  5. the move: read the bound

    the line:
    C∈O(n)C \in O(n)

    why it is allowed: By line 4, with the fixed multiple 2. ∈\in reads is in, and O(n)O(n) means at most a fixed multiple of nn, from some nn on.

  6. the move: a floor

    the line:
    C≥nC \ge n

    why it is allowed: 2n−12n - 1 is nn plus n−1n - 1, and from 1 up, n−1n - 1 is at least 0. For 4, CC is 7, at least 4.

  7. the move: read the bound

    the line:
    C∈Ω(n)C \in \Omega(n)

    why it is allowed: By line 6, with the fixed multiple 1. Ω(n)\Omega(n) means at least a fixed multiple of nn, above 0, from some nn on.

  8. the move: both together

    the line:
    C∈Θ(n)C \in \Theta(n)

    why it is allowed: Lines 5 and 7 bound CC by the same growth, only a fixed multiple apart. Θ(n)\Theta(n) means both.

try it with a small nn: at n=4n = 4, line 1 gives C=7C = 7, which you can work out by hand

Question 2: how many calls, RR, does the memo answer, from 2 up?
  1. the move: the second ask finds it

    the line:
    from F(3) up, the secondask is in the memo\begin{gathered} \text{from F(3) up, the second} \\ \text{ask is in the memo} \end{gathered}
    worked outfirst asksecond ask
    F(2)F(1), worked outF(0), worked out
    F(3)F(2), worked outF(1), answered
    F(4)F(3), worked outF(2), answered
    F(5)F(4), worked outF(3), answered
    F(5)'s run, each number worked out with its two asks, smallest first.

    why it is allowed: F(k) asks for F(k - 1) first. From 3 up, that call works out F(k - 2) on its way. So when F(k) asks for F(k - 2), the memo holds it.

  2. the move: one for each

    the line:
    R=n−2R = n - 2

    why it is allowed: So one answered call for each of F(3) to F(n), which is n−2n - 2 numbers. Every first ask comes on the first run down, before its number is written, so it is worked out. So is F(2)'s second ask, F(0). For 4, 2.

  3. the move: the same from question 1

    the line:
    R=(2n−1)−(n+1)R = (2n - 1) - (n + 1)

    why it is allowed: Every call is worked out or answered. From 2 up, F(0) to F(n) are worked out once each, which is n+1n + 1 calls. Question 1's 2n−12n - 1 less those is n−2n - 2. For 4, 7 less 5, which is 2.

try it with a small nn: at n=4n = 4, line 2 gives R=2R = 2, which you can work out by hand

Question 3: how fast must the plain method's calls grow? Take an even nn, twice a number mm: for 6, mm is 3. Let LL be a floor, a number the calls never fall below.
  1. the move: count the calls

    the line:
    calls for n:1+ the calls for n−1and for n−2\begin{gathered} \text{calls for } n \text{:} \\ 1 + \text{ the calls for } n - 1 \\ \text{and for } n - 2 \end{gathered}
    ncallshow
    01asks for nothing
    11asks for nothing
    231 + 1 + 1
    351 + 3 + 1
    491 + 5 + 3
    5151 + 9 + 5
    6251 + 15 + 9
    From 2 up, each row is 1 for its first call, plus the 2 rows just above.

    why it is allowed: From 2 up, the first call counts 1, and it asks for 2 smaller numbers. Each makes all its own calls, as nothing is written down.

  2. the move: more means more

    the line:
    the calls for n−1 are atleast those for n−2\begin{gathered} \text{the calls for } n - 1 \text{ are at} \\ \text{least those for } n - 2 \end{gathered}

    why it is allowed: F(5) first asks for F(4), so it makes all F(4)'s calls and more, 15 against 9. The same holds from 2 up. 1 and 0 make 1 each.

  3. the move: leave out the 1

    the line:
    the calls for n are morethan those for n−1and n−2 added up\begin{gathered} \text{the calls for } n \text{ are more} \\ \text{than those for } n - 1 \\ \text{and } n - 2 \text{ added up} \end{gathered}

    why it is allowed: Line 1, without the first call's 1. For 6, 25 is more than 15 + 9, which is 24.

  4. the move: swap for the smaller

    the line:
    the calls for n are atleast 2 times those for n−2\begin{gathered} \text{the calls for } n \text{ are at} \\ \text{least } 2 \text{ times those for } n - 2 \end{gathered}

    why it is allowed: By line 2, the calls for n−1n - 1 are at least those for n−2n - 2. For 6, 25 is at least 2 times 9.

  5. the move: repeat from 0

    the line:
    L=2mL = 2^m
    nmat leastcounted
    0011
    2123
    4249
    63825
    841667
    301532,7682,692,537
    The floor doubling, against the calls as counted.

    why it is allowed: 0 makes 1 call. By line 4, each 2 added at least doubles the calls. An even nn is 2 added mm times, so it makes at least mm 2s multiplied together. Name that LL.

  6. the move: what it says

    the line:
    2 more at leastdouble the calls\begin{gathered} \text{2 more at least} \\ \text{double the calls} \end{gathered}

    why it is allowed: Line 4 in words, and line 5 is the floor it gives. For 30, mm is 15, so at least 32,768 calls, and counted, 2,692,537.

try it with a small mm: at m=2m = 2, line 5 gives L=4L = 4, which you can work out by hand

Question 4: exactly how many calls does the plain method make? Let EE be n+1n + 1, the place one on from nn.
  1. the move: add 1 to each side

    the line:
    calls for n,+1, is(calls for n−1,+1)+(calls for n−2,+1)\begin{gathered} \text{calls for } n, + 1, \text{ is} \\ (\text{calls for } n - 1, + 1) \\ + (\text{calls for } n - 2, + 1) \end{gathered}

    why it is allowed: From 2 up, the calls for nn are 1, for the first call, plus the calls for n−1n - 1 and for n−2n - 2. Add 1 to each side, and the right has one 1 for each bracket. For 6, 25 + 1 is (15 + 1) + (9 + 1).

  2. the move: the rule again

    the line:
    read down, calls + 1 addsthe two before it\begin{gathered} \text{read down, calls + 1 adds} \\ \text{the two before it} \end{gathered}
    ncalls + 1half of thatF(n + 1)
    0211
    1211
    2422
    3633
    41055
    51688
    6261313
    Calls plus 1, halved, is the next Fibonacci number.

    why it is allowed: That is the rule of the Fibonacci numbers themselves. Calls + 1 starts 2, 2, then 4, 6, 10. Halved, that is 1, 1, 2, 3, 5.

  3. the move: name the place

    the line:
    E=n+1E = n + 1

    why it is allowed: At 0 and 1, halved, it gives F(1) and F(2), and each row goes on the same, the Fibonacci number one place on from nn. For 6, EE is 7.

  4. the move: twice that

    the line:
    calls for n,+1,is 2×F(E)\begin{gathered} \text{calls for } n, + 1, \\ \text{is } 2 \times \text{F}(E) \end{gathered}

    why it is allowed: Twice F(1) and twice F(2) start it, and each later one adds the two before it, as the Fibonacci numbers do. So it stays twice. For 6, 26 is 2 times 13.

  5. the move: the calls

    the line:
    calls for n is2×F(E)−1\begin{gathered} \text{calls for } n \text{ is} \\ 2 \times \text{F}(E) - 1 \end{gathered}

    why it is allowed: Take the 1 back off. For 6, F(7) is 13, so 25. So the plain method's calls grow as fast as its answers do, as the books say (volume three, chapter 38). Counted, from 20 up, each 1 more multiplies them by about 1.618, as 13,529 calls at 19 become 21,891 at 20.

try it with a small nn: at n=4n = 4, line 3 gives E=5E = 5, which you can work out by hand

Question 5: why is every number in the memo right, and how many does it end with? Let AA be how many, from 2 up.
  1. the move: the promise

    the line:
    every number written incell k is F(k)\begin{gathered} \text{every number written in} \\ \text{cell } k \text{ is F}(k) \end{gathered}

    why it is allowed: This is what to prove, and lines 2 and 3 prove it. A call writes only at its end, so what it adds was written earlier.

  2. the move: it starts true

    the line:
    the first numbers writtenare F(1) and F(0)\begin{gathered} \text{the first numbers written} \\ \text{are F(1) and F(0)} \end{gathered}

    why it is allowed: F(1) is 1 and F(0) is 0, by the rule. From 2 up, they come first. A call asks for F(k - 1) first, so the run goes straight down to F(1), and then F(2) asks for F(0).

  3. the move: one more

    the line:
    adding two right answerswrites a right number\begin{gathered} \text{adding two right answers} \\ \text{writes a right number} \end{gathered}
    writtencellnumberhow
    first11by the rule
    second00by the rule
    third211 + 0
    fourth321 + 1
    fifth432 + 1
    The memo of F(4), in the order written. Each sum reads two cells already written, so F(2) being right makes F(3) right.

    why it is allowed: A call on F(k) adds the answers for F(k - 1) and F(k - 2). Each was written before this one, so each is right by the promise so far. By the rule, their sum is F(k). So the promise carries on to each next number.

  4. the move: a read is as good

    the line:
    a number read is whatworking it out would give\begin{gathered} \text{a number read is what} \\ \text{working it out would give} \end{gathered}

    why it is allowed: F(k) depends on kk alone, so asking twice gets one answer. A method that also read today's date could not be kept this way, as the books warn (volume three, chapter 38).

  5. the move: how many

    the line:
    A=n+1A = n + 1

    why it is allowed: F(n) asks all the way down, so from 2 up, each of F(0) to F(n) is written once. For 4, the memo ends 0, 1, 1, 2, 3, which is 5.

try it with a small nn: at n=4n = 4, line 5 gives A=5A = 5, which you can work out by hand

Question 6: at most how many calls, DD, are waiting at once, from 1 up?
  1. the move: each asks for less

    the line:
    the calls waiting holddifferent numbers\begin{gathered} \text{the calls waiting hold} \\ \text{different numbers} \end{gathered}

    why it is allowed: The watch page stacks every call that has begun and not ended, the newest on top, as section 1's drawings show. Each call above another was asked for by it, for a smaller number. So they go down, with no number twice.

  2. the move: not both 1 and 0

    the line:
    F(1) and F(0) neverstand together\begin{gathered} \text{F(1) and F(0) never} \\ \text{stand together} \end{gathered}
    stepwhat happenscalls waiting
    4asks for F(1)F4, F3, F2, F1
    5writes F(1)F4, F3, F2
    6asks for F(0)F4, F3, F2, F0
    7writes F(0)F4, F3, F2
    8writes F(2)F4, F3
    F(4)'s run at the end of its first run down, the newest last. F0 comes only after F1 has gone.

    why it is allowed: Only F(2) asks for F(0), and its F(1) has ended by then. F(3)'s ask for F(1) is answered, so it never stands. So at most F(n) down to F(2), and one more.

  3. the move: the first run down

    the line:
    D=nD = n

    why it is allowed: That is nn calls, and the first run down reaches it, F(n) to F(1). For 4, the 4 calls F4, F3, F2 and F1.

  4. the move: the room they take

    the line:
    at most (n+1)+n in all,from 2 up: the memoand the calls\begin{gathered} \text{at most } (n + 1) + n \text{ in all,} \\ \text{from 2 up: the memo} \\ \text{and the calls} \end{gathered}

    why it is allowed: Each call waiting takes room too, to keep its place. Question 5's n+1n + 1 numbers and these nn calls are only a ceiling. When the calls are most, the memo holds at most 1 number. For 4, at most 5 + 4, which is 9. On the watch page, filled cells and calls together never pass 5.

try it with a small nn: at n=4n = 4, line 3 gives D=4D = 4, which you can work out by hand

Question 7: what does the whole method cost, from 2 up? Let TT be its looks, additions and writes.
  1. the move: count the steps

    the line:
    T=(2n−1)+(n−1)+(n+1)T = (2n - 1) + (n - 1) + (n + 1)
    F(4)how many
    looks in the memo7
    additions3
    writes5
    The steps of F(4), 15 in all.

    why it is allowed: Each call looks in the memo once, question 1's 2n−12n - 1. F(2) to F(n) each add once, n−1n - 1 additions. F(0) to F(n) are each written once, n+1n + 1 writes. For 4, 7 + 3 + 5, which is 15.

  2. the move: add them up

    the line:
    T=4n−1T = 4n - 1

    why it is allowed: 2 lots of nn, then nn, then nn, make 4 lots of nn. The rest, less 1, less 1 and plus 1, leave less 1. For 4, 15.

  3. the move: a ceiling

    the line:
    T≤4nT \le 4n

    why it is allowed: Taking 1 away leaves less. For 4, TT is 15, at most 16.

  4. the move: read the bound

    the line:
    T∈O(n)T \in O(n)

    why it is allowed: By line 3, with the fixed multiple 4. This is the rule on the page on solving each smaller problem once, at most n+1n + 1 different problems times a fixed few steps each.

  5. the move: a floor

    the line:
    T≥nT \ge n

    why it is allowed: From 2 up, 4n−14n - 1 is more than nn. For 4, TT is 15, at least 4.

  6. the move: read the bound

    the line:
    T∈Ω(n)T \in \Omega(n)

    why it is allowed: By line 5, with the fixed multiple 1.

  7. the move: both together

    the line:
    T∈Θ(n)T \in \Theta(n)

    why it is allowed: Lines 4 and 6 bound TT by the same growth.

  8. the move: while the numbers fit

    the line:
    each addition is a fixed fewactions only while thenumbers fit\begin{gathered} \text{each addition is a fixed few} \\ \text{actions only while the} \\ \text{numbers fit} \end{gathered}

    why it is allowed: Many languages keep a whole number in a fixed 64 binary digits, one of them for its sign. F(92) is the last that fits. Python's grow to fit, and an addition takes longer the more digits it adds. F(1000) has 209 ordinary digits. The steps stay as counted, and additions of long numbers cost more.

try it with a small nn: at n=4n = 4, line 1 gives T=15T = 15, which you can work out by hand

count it yourself

F(4), step by step. Each step lists the memo's filled cells in order, as they stand. A call the memo answers adds to both counts on its own step.

4, every step written down
stepthe memowhat happenstimes askedanswered from the memory
1Ask for F(4). The memory is empty, so it has to be worked out.10
2To work out F(4), first ask for F(3). It is not in the memory yet.20
3To work out F(3), first ask for F(2). It is not in the memory yet.30
4To work out F(2), first ask for F(1). It is not in the memory yet.40
51F(1) is 1 by the rule, so write 1 in the memory.140
61F(2) also needs F(0), so ask for it next. It is not in the memory yet.150
70, 1F(0) is 0 by the rule, so write 0 in the memory.0, 150
80, 1, 1F(2) is 1 + 0 = 1. Write it in the memory.0, 1, 150
90, 1, 1F(1) is in the memory already: 1. No need to work it out again.0, 1, 161
100, 1, 1, 2F(3) is 1 + 1 = 2. Write it in the memory.0, 1, 1, 261
110, 1, 1, 2F(2) is in the memory already: 1. No need to work it out again.0, 1, 1, 272
120, 1, 1, 2, 3F(4) is 2 + 1 = 3. Write it in the memory.0, 1, 1, 2, 372
130, 1, 1, 2, 3Done: F(4) is 3.0, 1, 1, 2, 372

In all, 7 times asked. The formula from section 4, 2n−12n - 1, gives C=7C = 7 at n=4n = 4: the same.

where you meet it

Donald Michie named it in the 1960s, and ready-made code offers it now.

  • Michie's memo functions

    Donald Michie described memo functions in Nature in 1968, after a 1967 memorandum: a function that keeps what it has worked out, and looks there first.

    source: D. Michie, Memo functions and machine learning (opens in a new tab), Nature 218, his list of publications (opens in a new tab), and the books' volume three, chapter 38

  • Python's cache

    Python's standard library offers this ready-made. Import cache from functools, write @cache above a function, and every answer is kept by what the function was given.

    source: the Python documentation, cache in functools (opens in a new tab)

  • ccache

    A compiler turns each file of code into one piece of a program. ccache keeps that piece, filed under a short label, a hash, worked out from the file, the other files it pulls in, the compiler and its options. When that label comes up again, nothing is compiled. Leave one of those out of the hash, and when it changes, a stale answer can come back, as the books warn.

    source: the ccache manual (opens in a new tab), and the books' volume three, chapter 38

what is used instead

To fill every number up to nn anyway, use a table, as section 7 shows: no calls wait. For one far-off number, other methods halve nn again and again, which this page does not derive.

how it compares

The plain method has no memo. This page's method works top-down, from the big question down. A table has no calls: it fills from the left, and each cell reads the two before it. Keep only the last two numbers, and that is all the memory it needs, though earlier numbers are then gone. A memo suits a problem where many smaller problems are never asked for. From 2 up, every smaller number is asked for here, so a table does as well, with nothing waiting.

waywork on F(30)most waitingnumbers kept
plain method2,692,537 calls30none
with a memo59 calls3031
a table29 additionsnone31
a table, the last two only29 additionsnone2
A call and an addition are different steps, so read this for the size of each number. The memo's 59 calls hold 29 additions, as question 7 counts.
cell 0 holds 00012345cell 1 holds 100112345cell 2: 1 + 0 = 1001112345cell 3: 1 + 1 = 20011122345cell 4: 2 + 1 = 300111223345cell 5: 3 + 2 = 5001112233455
The table for F(5), filling from the left, one row for each cell written. Arrows show what each cell reads. Under each cell, its number.
ncalls, plaincalls, with a memoplain per memo call
51591.7
10177199.3
2021,89139561.3
302,692,5375945,636.2
Each row counted by running the method.