N-th Tribonacci Number

Find the n-th number of a sequence where each number is the sum of the three before it.

The Tribonacci sequence starts with T(0) = 0, T(1) = 1 and T(2) = 1. Every later number is the sum of the three numbers just before it: T(n) = T(n - 1) + T(n - 2) + T(n - 3) for n ≥ 3. Given a whole number n with 0 ≤ n ≤ 37, return T(n).

Example 1
Input: n = 4
Output: 4
Explanation: T(3) = 0 + 1 + 1 = 2, and T(4) = 1 + 1 + 2 = 4.
Example 2
Input: n = 25
Output: 1389537
Solution

The Idea

Picture a row of boxes numbered 0, 1, 2 and so on. The first three boxes hold 0, 1 and 1. To fill any other box, add up the three boxes just to its left. The number in box i is T(i), the i-th Tribonacci number.

Example 1 asks for T(4). Box 3 gets 0 + 1 + 1 = 2, and box 4 gets 1 + 1 + 2 = 4, which is the answer. Look at the picture below.

Boxes T(0) to T(7) holding 0, 1, 1, 2, 4, 7, 13, 24. T(4) = 4 is highlighted, and the three boxes before it, T(1), T(2) and T(3), are marked: 1 + 1 + 2 = 4.

The orange box, T(4), holds 4. The three teal boxes under the label "the three values before it" are T(1), T(2) and T(3), and 1 + 1 + 2 = 4. The grey boxes on the right are computed later, the same way: T(5) is 1 + 2 + 4 = 7.

The rule also reads from the top down. To get T(25), ask for T(24), T(23) and T(22). Each of those asks for three more, and the same smaller values get asked for over and over. How much of that work is new?

Very little. There are only 26 different boxes from T(0) to T(25), and each one needs just the three to its left. So fill the boxes from left to right, and every box is ready by the time a later box needs it. Filling the row this way, so each new box reuses boxes already filled instead of working them out again, is called dynamic programming.

Look at the picture once more: box T(0) plays no part in T(4), and it will play no part in T(5) either. Each step reads only the three boxes before it, so three numbers are all that has to be kept.

Solution Approach

Turning the row of boxes into code means settling three things: why calling the rule top-down is slow, how to fill the row while keeping only three values, and whether a Java int is big enough for the answer.

Calling the rule directly

Why not write the rule as a method that calls itself for n - 1, n - 2 and n - 3? Each call starts three more calls, and none of them knows what another call already worked out. For n = 25 that makes 2,700,421 calls, counted by the program below. Filling the boxes from left to right needs 23 sums, one for each box from T(3) to T(25).

Storing each result of that method in an array, so that a repeated call reads the stored box instead of working it out again, also makes it fast. Filling the boxes from left to right gets the same speed without the array.

Keeping three values

How many boxes does the loop need at a time? Only three, the three to the left of the box being filled. The code keeps them in variables named a, b and c, holding T(i - 3), T(i - 2) and T(i - 1). The new box is a + b + c.

After each sum, the three slide one box to the right: a takes the value of b, b takes the value of c, and c takes the new sum. Copying in that order moves each value before it is overwritten.

Where does the loop start? T(0), T(1) and T(2) are given, so the method returns them straight away. For anything larger, the loop starts at T(3) with a = 0, b = 1 and c = 1.

The size of the answer

Will the answer fit in an int? From T(4) on, each number is nearly double the one before, so the row grows fast. T(37), the largest n allowed, is 2,082,876,103, just under 2,147,483,647, the top of the int range. T(38) would be 3,831,006,429, and an int sum that large wraps around to a negative number. That is where the limit n ≤ 37 comes from.

Java Solution

The method tribonacci works in these steps:

  1. First, handle the three given values: return 0 when n is 0, and 1 when n is 1 or 2.
  2. Set up the three boxes before T(3) in variables a = 0, b = 1 and c = 1.
  3. Run a loop with i from 3 up to n. Each pass adds the three into next, which is T(i), then slides the values along: a = b, b = c, c = next.
  4. After the last pass, c holds T(n), and the method returns it.

The main method runs both examples, the small inputs 0 and 2, the limit 37 and one past it, 38. It also prints T(0) to T(7) and counts the calls that the plain recursive method, slow, makes for n = 25.

Java
public class NthTribonacciNumber {

    public static int tribonacci(int n) {
        if (n == 0) {
            return 0;
        }
        if (n <= 2) {
            return 1;
        }
        int a = 0;                // T(i - 3)
        int b = 1;                // T(i - 2)
        int c = 1;                // T(i - 1)
        for (int i = 3; i <= n; i++) {
            int next = a + b + c; // T(i)
            a = b;                // slide the three values one place along
            b = c;
            c = next;
        }
        return c;
    }

    static long calls = 0;

    static int slow(int n) {      // the plain recursion, for counting calls only
        calls++;
        if (n == 0) {
            return 0;
        }
        if (n <= 2) {
            return 1;
        }
        return slow(n - 1) + slow(n - 2) + slow(n - 3);
    }

    public static void main(String[] args) {
        System.out.println("n = 4:  " + tribonacci(4));
        System.out.println("n = 25: " + tribonacci(25));
        System.out.println("n = 0:  " + tribonacci(0));
        System.out.println("n = 2:  " + tribonacci(2));
        System.out.println("n = 37: " + tribonacci(37));
        System.out.println("n = 38: " + tribonacci(38) + " (too big for an int)");

        StringBuilder row = new StringBuilder("T(0) to T(7):");
        for (int n = 0; n <= 7; n++) {
            row.append(' ').append(tribonacci(n));
        }
        System.out.println(row);

        int value = slow(25);
        System.out.println("plain recursion for n = 25: " + value + " after " + calls + " calls");
    }
}

Running it prints:

Output
n = 4:  4
n = 25: 1389537
n = 0:  0
n = 2:  1
n = 37: 2082876103
n = 38: -463960867 (too big for an int)
T(0) to T(7): 0 1 1 2 4 7 13 24
plain recursion for n = 25: 1389537 after 2700421 calls

The answers 4 and 1389537 match Examples 1 and 2, and n = 0 and n = 2 return 0 and 1 before the loop runs. For n = 37 the result, 2082876103, is still positive. Look at the line for n = 38: it prints -463960867. The true value, 3,831,006,429, does not fit, so the int sum wrapped around.

The row T(0) to T(7) reads 0 1 1 2 4 7 13 24, the numbers in the boxes of the picture. The last line shows the cost of the plain recursion: the same 1389537, but after 2,700,421 calls, where the loop made 23 passes.

Complexity

The loop does a fixed amount of work for each box from T(3) to T(n).

  • Time: O(n), because each of the n - 2 passes fills one box with two additions and three copies.
  • Space: O(1), because the method keeps only a, b, c and next however large n is, never the whole row of n + 1 boxes.

Climbing Stairs builds each answer from the two before it instead of three.