Implementation
FibonacciRecursivo.cpp
I/O optimizations
Themain function disables synchronization between C and C++ I/O streams (ios_base::sync_with_stdio(false)) and unties cin from cout (cin.tie(nullptr)). These two lines reduce I/O overhead and are standard practice in competitive programming.
Return type
Thefibonacci function returns long rather than int. This lets it represent values up to at least 2,147,483,647 on 32-bit long platforms and up to 9,223,372,036,854,775,807 on 64-bit platforms, safely covering the typical range of Fibonacci inputs.
Recursive logic
- Base case — when
n == 1orn == 2, the function returns1directly. - Recursive case — for
n > 2, the function returns the sum of the two preceding Fibonacci values by calling itself twice:fibonacci(n - 1) + fibonacci(n - 2).
n = 5 the call tree looks like:
1.
How to compile and run
Example values
Input (n) | Output F(n) |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 5 | 5 |
| 10 | 55 |
| 20 | 6765 |
Complexity and limitations
The
fibonacci function recomputes the same sub-problems many times. For example, fibonacci(5) calls fibonacci(3) twice and fibonacci(2) three times. This repeated work makes the algorithm’s time complexity O(2^n).