- How the Tribonacci sequence generalizes Fibonacci: each term is the sum of the previous three
- Why
a = b; b = c; c = next;is the correct rotation order β and what happens if you do it wrong - Why a three-variable sliding window is enough, with no array needed
- Why the sequence is O(N) in time and O(1) in space
- How to generalize the pattern to a k-step recurrence (Tetranacci, Pentanacci, β¦)
What Is the Tribonacci Sequence?
The Fibonacci sequence is defined by a simple rule: each term is the sum of the previous two. The Tribonacci sequence is the natural generalization: each term is the sum of the previous three. The standard seed values are 0, 0, 1, giving the sequence 0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, β¦. Some textbooks use 0, 1, 1 as seeds, which produces a different (but still valid) sequence β the choice is a convention, and both are widely used.
The recurrence relation is T(n) = T(n-1) + T(n-2) + T(n-3) for n β₯ 3, with the seeds T(0) = 0, T(1) = 0, T(2) = 1. Unlike Fibonacci, whose closed form involves the golden ratio, Tribonacci's closed form involves the real root of xΒ³ = xΒ² + x + 1, approximately 1.839286 β called the Tribonacci constant. The sequence grows roughly like 1.839βΏ, which is slower than Fibonacci's 1.618βΏ but still exponentially fast.
What makes Tribonacci a good loop exercise is the need for three sliding variables, not two. Fibonacci is a two-variable dance; Tribonacci is a three-variable dance, and the rotation order matters. Get the order wrong and you'll overwrite a variable before using it, producing a totally different sequence. That's the small trap in this program.
π‘ In one line: maintain three variables a, b, c; each iteration prints c, computes next = a + b + c, then rotates a = b, b = c, c = next.
The Sliding-Window Algorithm
In pseudocode, the whole thing is a single while loop:
a = 0; b = 0; c = 1; i = 0
while i < N:
print c
next = a + b + c
a = b; b = c; c = next
i = i + 1
That's the whole algorithm. The three variables a, b, c form a sliding window over the last three terms. Each iteration, the window moves forward by one β the oldest term (a) is dropped, and the new term (next) becomes c. The sequence is printed as it's generated, so no array is needed. Space complexity: O(1).
| Iteration | a | b | c | Printed | next = a+b+c |
|---|---|---|---|---|---|
| start | 0 | 0 | 1 | β | β |
| 1 | 0 | 0 | 1 | 1 | 1 |
| 2 | 0 | 1 | 1 | 1 | 2 |
| 3 | 1 | 1 | 2 | 2 | 4 |
| 4 | 1 | 2 | 4 | 4 | 7 |
| 5 | 2 | 4 | 7 | 7 | 13 |
| 6 | 4 | 7 | 13 | 13 | 24 |
| 7 | 7 | 13 | 24 | 24 | 44 |
| 8 | 13 | 24 | 44 | 44 | 81 |
| 9 | 24 | 44 | 81 | 81 | 149 |
The sequence printed is 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, β¦ for N = 10. (Some conventions print 0, 0, 1, 1, 2, 4, β¦ starting from the seeds. The variant below prints from the first seed, which includes the two zeros. Both are correct β the choice is a convention.)
Complete C Program
Program: generate the first N Tribonacci numbers using a while loop
#include <stdio.h>
int main(void) {
int n;
printf("Enter the number of terms (N): ");
if (scanf("%d", &n) != 1 || n < 1) {
printf("Invalid input. Enter a positive integer.\n");
return 1;
}
long long a = 0, b = 0, c = 1; /* seeds: 0, 0, 1 */
int i = 0;
printf("Tribonacci sequence (first %d terms):\n", n);
while (i < n) {
printf("%lld ", c);
long long next = a + b + c;
a = b;
b = c;
c = next;
i++;
}
printf("\n");
return 0;
}
And here's a variant that prints all three seeds first, matching the canonical sequence 0, 0, 1, 1, 2, 4, 7, β¦ more explicitly:
Variant printing from the very first seed
#include <stdio.h>
int main(void) {
int n;
printf("Enter N: ");
scanf("%d", &n);
long long a = 0, b = 0, c = 1;
printf("0 0 1 ");
int count = 3; /* we've already printed three terms */
while (count < n) {
long long next = a + b + c;
printf("%lld ", next);
a = b;
b = c;
c = next;
count++;
}
printf("\n");
return 0;
}
The first version is the cleaner one to submit β the loop structure is uniform, and the interpretation "print the term, then advance" is clear. The second version handles the seeds explicitly and is useful if the assignment expects the sequence to start exactly at 0.
Program Output
Enter the number of terms (N): 10
Tribonacci sequence (first 10 terms):
1 1 2 4 7 13 24 44 81 149
With the seed-printing variant, the same N = 10 produces:
0 0 1 1 2 4 7 13 24 44
Both are valid Tribonacci sequences β the only difference is where you stop. The canonical OEIS sequence A000073 starts 0, 0, 1, 1, 2, 4, 7, 13, 24, 44, β¦. Input N = 1 should produce a single term. Input N = 3 gives the seeds 0, 0, 1 (or 1, 1, 2 with the simpler variant).
Step-by-Step Explanation
Let's walk through the simpler variant for N = 6, watching the three variables rotate.
1. Reading and validating input
scanf("%d", &n) reads N. The validation n < 1 rejects zero and negatives because the sequence always has at least one term. There's no upper bound enforced, but long long overflows around N = 60 (the Tribonacci growth rate of 1.839βΏ reaches 2βΆΒ³ in about 60 terms). For safety, you could cap N at 60.
2. The seed values
a = 0, b = 0, c = 1. These are the first three Tribonacci numbers in the standard convention. They're initialized before the loop, and they're the state the loop depends on. The variable c holds the "current" term β the one about to be printed β and a and b hold the two that came before it.
3. The rotation order β the only subtle point
Inside the loop body, the order is critical:
next = a + b + c;β compute the next term, using all three variables while they still hold their correct values.a = b;β shift the oldest term out, the middle term becomes the oldest.b = c;β the current term becomes the middle term.c = next;β the newly computed term becomes the current term.
If you reverse the order β say c = next; b = c; a = b; β then after the first assignment c already holds the new value, so b = c copies the new value instead of the old one, and a = b copies that, and you lose the whole history. The result is a completely different (and wrong) sequence. The order a = b; b = c; c = next; is correct precisely because each assignment uses the value from before the previous assignment, and none of the right-hand sides depend on a variable that was just overwritten.
4. Watching N = 6
Starting state: a = 0, b = 0, c = 1.
- Iteration 1: print 1;
next = 0 + 0 + 1 = 1; rotate toa = 0, b = 1, c = 1. - Iteration 2: print 1;
next = 0 + 1 + 1 = 2; rotate toa = 1, b = 1, c = 2. - Iteration 3: print 2;
next = 1 + 1 + 2 = 4; rotate toa = 1, b = 2, c = 4. - Iteration 4: print 4;
next = 1 + 2 + 4 = 7; rotate toa = 2, b = 4, c = 7. - Iteration 5: print 7;
next = 2 + 4 + 7 = 13; rotate toa = 4, b = 7, c = 13. - Iteration 6: print 13;
next = 4 + 7 + 13 = 24; rotate toa = 7, b = 13, c = 24. i = 6, conditioni < 6false β loop exits.
Printed: 1 1 2 4 7 13. That matches the first six terms starting from c = 1. Note the pattern of rotations β the entire state shifts one slot to the left, and the new term enters at c. It's the same operation as a queue, just implemented with three named variables.
5. Why O(N) time and O(1) space
The loop runs N times, and each iteration does constant work β three additions, three assignments, one printf. Total time: O(N). The variables used are a, b, c, next, i β a fixed set, regardless of N. Total space: O(1). This is strictly better than storing all N terms in an array (O(N) space), which would be necessary if you needed random access to a specific term, but is wasteful for pure sequential output.
6. Why the variable type must be long long
The Tribonacci sequence grows at about 1.839βΏ. At N = 40, the value is around 1.4 Γ 10βΉ (fits in 32-bit int). At N = 50, it's around 4.5 Γ 10ΒΉΒΉ (exceeds int). At N = 60, it's around 8 Γ 10ΒΉβ΄ (fits in long long). At N = 80, it overflows 64-bit entirely. So long long covers N up to about 60; use unsigned long long for a bit more range, or a bignum library beyond that.
7. Generalizing to k-step recurrences
The same pattern extends to any k-step recurrence β Tetranacci (sum of last four), Pentanacci (sum of last five), and so on. You just need k variables (or a circular buffer of size k), and the rotation becomes a shift. For k = 4: d = a + b + c + d; a = b; b = c; c = d; β wait, that overwrites d before using it. The correct form is next = a + b + c + d; a = b; b = c; c = d; d = next;. Same lesson: compute the new value into a temporary first, then shift.
π― Remember this: three variables a, b, c hold the last three terms. Compute next first, then rotate a = b; b = c; c = next; in that order. Print c before rotating to output the term. Use long long for N up to 60.
Frequently Asked Questions
1. Why does the sequence start at 0, 0, 1 and not 0, 1, 1?
Both conventions are used, and the choice is somewhat arbitrary. The OEIS entry for the Tribonacci numbers (A000073) uses 0, 0, 1 as seeds, giving 0, 0, 1, 1, 2, 4, 7, 13, β¦. Some textbooks use 0, 1, 1 to make the sequence start at 0 without a repeat, giving 0, 1, 1, 2, 4, 7, β¦. Either is mathematically valid as long as you're consistent; for an assignment, follow whatever the problem statement specifies.
2. Why does the rotation order matter so much?
Because each assignment overwrites a variable that the next assignment uses. If you write a = b; b = c; c = next; in that order, then b = c uses the original c (before it was updated), and a = b uses the original b. If you reverse the order to c = next; b = c; a = b;, then b = c copies the new c (the just-computed next), and a = b copies that β losing the original values. The correct pattern is to compute into a temporary, then shift from oldest to newest.
3. Can I use an array instead of three variables?
Yes. An array t[N] with t[0] = 0, t[1] = 0, t[2] = 1 and t[i] = t[i-1] + t[i-2] + t[i-3] for i β₯ 3 works just as well. The tradeoff: the array version uses O(N) space but allows random access to any term after the loop finishes. The three-variable version is O(1) space but forgets earlier terms once they rotate out. For the assignment ("generate the first N terms"), the three-variable version is the more elegant solution.
4. What's the difference between Tribonacci and Fibonacci?
Fibonacci: each term is the sum of the previous two. Tribonacci: each term is the sum of the previous three. Fibonacci grows at ~1.618βΏ (the golden ratio); Tribonacci grows at ~1.839βΏ (the Tribonacci constant). Both are exponentially fast, but Tribonacci grows faster because it has more terms to sum. Tetranacci (sum of four) grows at ~1.927βΏ, and Pentanacci (sum of five) at ~1.966βΏ β approaching 2 as k increases.
5. Why use a while loop instead of a for loop?
Either works. The assignment specifies a while loop, and a while loop is natural here because we're tracking a counter that isn't directly the loop variable β the loop continues until we've printed N terms, and the term itself changes inside the body. A for loop with for (int i = 0; i < n; i++) would be equally clear. Choose based on what the problem asks for.
6. What if N is very large, like 1000?
The loop still runs N times, so it's fast β about 1000 iterations. But the values overflow long long around N = 60, so the printed sequence will be garbage after that. For large N, you'd need a bignum library (like GMP), or output only the last few digits via modular arithmetic. The algorithm's structure doesn't change, but the integer type has to.
π‘ Tip: After this program, try the Tetranacci sequence (sum of four): a = 0, b = 0, c = 0, d = 1, then next = a + b + c + d; a = b; b = c; c = d; d = next;. Then try the Padovan sequence (each term is the sum of the previous two, skipping one: P(n) = P(n-2) + P(n-3)) β it's a good exercise in generalizing the sliding-window idea.