|
Aleph-w 3.0
A C++ Library for Data Structures and Algorithms
|
Fibonacci sequence: Three implementation strategies compared. More...
Go to the source code of this file.
Classes | |
| struct | Item |
Macros | |
| #define | P0 0 |
| #define | P1 1 |
| #define | P2 2 |
| #define | N (stack.top().n) |
| #define | F1 (stack.top().f1) |
| #define | RESULT (stack.top().result) |
| #define | RETURN_POINT (stack.top().return_point) |
Functions | |
| int | fib_it (int n) |
| int | fib_rec (int n) |
| int | fib_st (int n) |
| int | main (int argc, char *argv[]) |
Fibonacci sequence: Three implementation strategies compared.
This example demonstrates three different approaches to computing the Fibonacci sequence, each illustrating important programming concepts. The Fibonacci sequence is one of the most famous sequences in mathematics and provides excellent examples of different algorithmic approaches.
The Fibonacci sequence is defined recursively as:
Sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
Strategy: Use loop with two variables to track previous values
Algorithm:
Characteristics:
Strategy: Direct translation of mathematical definition
Algorithm:
Problem: Many redundant calculations!
Call tree for F(5):
Characteristics:
Strategy: Simulate recursion using explicit stack
Algorithm:
Characteristics:
| Implementation | Time | Space | Redundancy | Best For |
|---|---|---|---|---|
| Iterative | O(n) | O(1) | None | Production |
| Recursive | O(2^n) | O(n) | Massive | Education |
| Stack-based | O(n) | O(n) | None | Learning |
Computing F(40):
This example teaches:
After studying this example, you understand:
Can optimize recursive version with memoization:
Time: O(n) - each value calculated once Space: O(n) - memoization table
Can compute F(n) in O(log n) time using matrix exponentiation:
Time: O(log n) - very fast!
⚠️ Warning: The recursive version is extremely slow for large n!
Use iterative or stack-based for large values.
Definition in file fib.C.
| int fib_it | ( | int | n | ) |
Definition at line 258 of file fib.C.
References Aleph::divide_and_conquer_partition_dp().
Referenced by main().
| int fib_rec | ( | int | n | ) |
| int fib_st | ( | int | n | ) |
Definition at line 299 of file fib.C.
References Aleph::divide_and_conquer_partition_dp(), Item::n, N, P1, P2, Aleph::ArrayStack< T >::pop(), Aleph::ArrayStack< T >::push(), RESULT, and Aleph::ArrayStack< T >::size().
Referenced by main().