Definition
0, 1 seeds
Fk = Fk-1 + Fk-2.
Fibonacci starts with 0 and 1; each next term is the sum of the previous two. This tutorial covers n-term printing, a value-ceiling variant, memoized recursion, a live preview, worked Python examples, edge cases, and complexity.
0, 1 seeds
Fk = Fk-1 + Fk-2.
(a, b) shift
Print a, then a, b = b, a + b.
n or ≤ M
Fixed term count or value ceiling.
O(φn)
Memoize or iterate for real work.
BigInt
Exact terms in the browser up to 500.
Iterative
Linear updates with O(1) extra space.
The Fibonacci series starts with seeds 0 and 1. Every next value is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13, …
It is a classic state-update pattern: keep two previous terms, print one, then move forward. Some books start with 1, 1 — the recurrence is the same; only indexing shifts.
It teaches loops, rolling state, and why naive recursion fails — skills that transfer to DP and sequence problems.
State the convention before coding.
(a, b) ← (b, a+b) streams the series.
Best default for printing many terms.
Values grow exponentially with k.
In short: print a starting at 0, then repeatedly replace (a, b) with (b, a + b).
Print the first n Fibonacci terms, or all terms up to a maximum value.
# seeds: 0, 1
# first 10: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
# <= 100: ... ends at 89 (next is 144) | Item | Type | Description |
|---|---|---|
n | int | Number of terms (positive for a non-empty series). |
max_val | int | Optional ceiling: print while term ≤ max_val. |
| Output | text | Space- or comma-separated Fibonacci numbers. |
function print_first_n_fibonacci_terms(n):
a = 0
b = 1
repeat n times:
output a
next = a + b
a = b
b = next | Method | Idea | Notes |
|---|---|---|
| Iterative series | Two-variable shift | Best for printing many terms |
| Until max | While a ≤ M | Different stop rule, same update |
| Memoized recursive | lru_cache on fib(k) | Good for single nth term |
| Goal | Pattern |
|---|---|
| Initialize | a, b = 0, 1 |
| Advance | a, b = b, a + b |
| n terms | for _ in range(n): ... |
| Until max | while a <= max_val: ... |
| First ten | 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 |
| Format cleanly | ", ".join(parts) |
Same recurrence — very different costs for series output.
a, b = b, a+bO(n) time, O(1) extra space
fib(n-1)+fib(n-2)Exponential recomputation
@lru_cacheO(n) for nth term with cache
iterate to printMention memo/matrix as follow-ups
Reach for Fibonacci when rolling state or sequence drills appear.
Classic loop and recursion-vs-iteration discussion.
Natural next step from product loops to recurrence.
Shows why overlapping subproblems need memoization.
Golden-ratio asymptotics make exponential growth concrete.
Print with a loop; reserve recursion for nth-term demos.
Key benefit: one short loop that teaches rolling state, stop conditions, and recursion tradeoffs.
Print the first n terms using exact BigInt arithmetic.
Three complete Python programs — first n terms, until a max value, and memoized recursive nth term. Click View Output to reveal sample console results.
Interview-style first-n-terms printer.
n = 10)Clean comma formatting with a two-variable update.
def display_fibonacci_terms(n: int) -> None:
if n <= 0:
print("Need a positive term count.")
return
first, second = 0, 1
parts = []
for _ in range(n):
parts.append(str(first))
first, second = second, first + second
print(f"Fibonacci series up to {n} terms: " + ", ".join(parts))
terms = 10
display_fibonacci_terms(terms) Two rolling values stream the series. Collecting strings in a list lets ", ".join(...) avoid trailing-comma bugs.
Same recurrence with a different stop rule.
Continue while the current term stays within the limit.
def display_fibonacci_until(max_val: int) -> None:
if max_val < 0:
print("max_val must be nonnegative.")
return
a, b = 0, 1
parts = []
while a <= max_val:
parts.append(str(a))
a, b = b, a + b
print(f"Fibonacci numbers <= {max_val}: " + " ".join(parts))
display_fibonacci_until(100) The first Fibonacci number greater than 100 is 144, so the printed list ends at 89.
Get the nth term without exponential recomputation.
fib(k)Use lru_cache when you need a single term, not a full print loop.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(k: int) -> int:
if k < 0:
raise ValueError("k must be nonnegative.")
if k <= 1:
return k
return fib(k - 1) + fib(k - 2)
# 0-based: fib(0)=0, fib(1)=1, ..., fib(9)=34
for k in range(10):
print(f"F({k}) = {fib(k)}") Without a cache, each call branches into two — exponential work. With lru_cache, each k is computed once (O(n) for F(n)). For printing a long series, prefer the iterative loop from Example 1.
Set a = 0, b = 1.
Output a as the next term.
Set a, b = b, a + b and repeat.
Stop after n terms or when a > max.
Trace the two-variable update starting from (0, 1).
| Step | (a, b) before | (a, b) after | |
|---|---|---|---|
| 1 | (0, 1) | 0 | (1, 1) |
| 2 | (1, 1) | 1 | (1, 2) |
| 3 | (1, 2) | 1 | (2, 3) |
| 4 | (2, 3) | 2 | (3, 5) |
| 5 | (3, 5) | 3 | (5, 8) |
| 6 | (5, 8) | 5 | (8, 13) |
Printed so far: 0, 1, 1, 2, 3, 5.
Where Fibonacci shows up beyond the interview prompt.
Rolling state and stop-condition practice.
Example: print first n terms.
Shows overlapping subproblems clearly.
Example: naive vs memoized fib.
Next classic sequence after product loops.
Example: this walkthrough chain.
List all terms up to a budget M.
Example: Fibonacci ≤ 100.
Golden ratio and exponential growth demos.
Example: Fk+1/Fk → φ.
Matrix exponentiation / fast doubling for huge n.
Example: O(log n) single term.
Pro Tip: say “seeds 0 and 1” before coding — indexing debates vanish.
Why this pattern works well in interviews and classwork.
Only two integers stream the entire series.
Same update for n terms or ≤ M.
First ten terms are easy to verify by eye.
Memoization, matrix pow, and φ asymptotics.
Pro Tip: lead with the iterative printer; offer memoized recursion only if asked for the nth term.
Small habits that keep Fibonacci solutions interview-ready.
Say 0, 1 (or 1, 1) before writing code.
Two variables beat naive recursion for printing.
Avoid trailing commas and messy separators.
Empty series or a clear message — pick one.
0…34 catches off-by-one shift bugs fast.
Pro Tip: Python ints grow freely — talk about time for huge terms, not C-style overflow.
Mistakes that commonly break Fibonacci solutions.
Calling fib(n) recursively to print many terms.
→ Use the two-variable iterative loop.
Mixing 0,1 with 1,1 without saying so.
→ State seeds explicitly in the answer.
Looping n-1 times or starting from 1 only.
→ Trace first 10 against 0…34.
Printing commas after every term including the last.
→ Collect then join.
Empty or bogus output when n ≤ 0.
→ Validate and message clearly.
Python avoids fixed-width overflow, but clarity and stop conditions still matter.
n ≤ 0Handle as empty/error depending on requirement.
Using join() avoids trailing comma issues.
Recomputes work exponentially; avoid for long series output.
State clearly whether the sequence starts with 0,1 or 1,1.
max_val = 100Last printed term is 89; next would be 144.
Exact but large — printing cost grows with digit count.
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
Quick Takeaway: keep two seeds, print the first, shift with a + b, and prefer iteration for series output.
| Task | Time | Extra space |
|---|---|---|
| First n terms (iterative) | O(n) | O(1) |
| All terms ≤ M | O(k) where k terms printed | O(1) |
| Naive fib(n) recursion | O(φn) | O(n) |
| Memoized fib(n) | O(n) | O(n) cache |
For interview printing tasks, the iterative approach is the right default. Extra space above ignores the output string/list size.
Fibonacci streams from seeds 0 and 1 by repeatedly replacing (a, b) with (b, a + b). Print with an iterative loop; use memoized recursion only when you need a single nth term.
Practice the three examples above, then continue to GCD for the classic Euclidean algorithm.
State seeds, avoid naive recursion for series printing, and verify against the first ten terms.
Stream the series the interview-friendly way.
0, 1
Definitiona, b = b, a+b
Coren or ≤ M
VariantsNaive recur
TrapO(n)
AnalysisThe ratio of consecutive terms Fk+1/Fk approaches the golden ratio φ = (1+√5)/2 as k grows.
Learn how to find the greatest common divisor with Euclidean division.
9 people found this page helpful