A recurrence relation defines each term of a sequence using earlier terms. Recursive programs produce recurrences, so analysing them needs this topic.

Idea

Instead of a formula for the n-th term, you give a rule and starting values. For example aₙ = aₙ₋₁ + 3 with a₁ = 2 gives 2, 5, 8, 11, ... The starting values are the initial conditions.

Modelling with recurrences

Fibonacci numbers. Each number is the sum of the two before: F(n) = F(n − 1) + F(n − 2), with F(0) = 0 and F(1) = 1. The sequence is 0, 1, 1, 2, 3, 5, 8, 13, ...

def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

print([fib(i) for i in range(8)])

Output:

[0, 1, 1, 2, 3, 5, 8, 13]

Tower of Hanoi. To move n disks from peg A to C using B: move n − 1 disks to B, move the largest disk to C, then move the n − 1 disks onto C. So T(n) = 2T(n − 1) + 1 with T(1) = 1. Computing: T(2) = 3, T(3) = 7, T(4) = 15, which suggests T(n) = 2ⁿ − 1. Moving 10 disks takes 1023 moves.

Other models.

  • Compound interest: Pₙ = 1.05 Pₙ₋₁ gives Pₙ = P₀ (1.05)ⁿ.
  • Binary strings with no two consecutive 0s: aₙ = aₙ₋₁ + aₙ₋₂, with a₁ = 2 and a₂ = 3.
  • Number of comparisons in a loop that halves its input: T(n) = T(n / 2) + 1.

Order and linearity

A relation is linear if each earlier term appears only to the first power and is not multiplied by another term, and it has constant coefficients if the multipliers are numbers. The order is the gap between the earliest and latest index. Fibonacci is linear, order 2, with constant coefficients. T(n) = 2T(n − 1) + 1 is linear of order 1 but non-homogeneous because of the + 1.

Common mistakes

  • Forgetting the initial conditions. A recurrence without them has many solutions.
  • Mixing up the number of moves (2ⁿ − 1) with the number of disks.

Practice questions

  1. What is a recurrence relation? What are initial conditions?
  2. Write the recurrence for Fibonacci numbers and give the first eight terms.
  3. Derive the recurrence for Tower of Hanoi and find T(5).
  4. Find the first four terms of aₙ = 2aₙ₋₁ + 1 with a₀ = 1.
  5. What does "linear with constant coefficients" mean?

Answers to the practice questions

  1. A rule giving a term from earlier terms; initial conditions are the starting values.
  2. F(n) = F(n − 1) + F(n − 2); 0, 1, 1, 2, 3, 5, 8, 13.
  3. T(n) = 2T(n − 1) + 1, T(1) = 1; T(5) = 31.
  4. 1, 3, 7, 15.
  5. Earlier terms appear only to the first power with numeric multipliers.

Sources

  • Official BCA syllabus Mathematics Foundations to Computer Science I, course code CC101, Unit II
  • Kolman, Busby and Ross, Discrete Mathematical Structures, 6th edition, Pearson