Skip to content

Commit e7dbcba

Browse files
authored
Recursive function writing is done
1 parent b1c02c4 commit e7dbcba

File tree

1 file changed

+38
-1
lines changed
  • allhands/spring2025/weekeleven/teamthree

1 file changed

+38
-1
lines changed

allhands/spring2025/weekeleven/teamthree/index.qmd

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,44 @@ TODO: Faaris to complete
2222

2323
### Generate Fibonacci using a Recursive approach
2424

25-
TODO: Duru- please explain your approach, including a code sample
25+
The recursive approach computes Fibonacci numbers by repeatedly calling the function itself. However, this method is highly inefficient because it recalculates the same values multiple times. For example, to compute fibonacci_recursive(5), the function computes fibonacci_recursive(2) three times:
26+
```python
27+
fibonacci_recursive(5)
28+
├── fibonacci_recursive(4)
29+
│ ├── fibonacci_recursive(3)
30+
│ │ ├── fibonacci_recursive(2)
31+
│ │ │ ├── fibonacci_recursive(1) → 1
32+
│ │ │ ├── fibonacci_recursive(0) → 0
33+
│ │ ├── fibonacci_recursive(1) → 1
34+
│ ├── fibonacci_recursive(2)
35+
│ ├── fibonacci_recursive(1) → 1
36+
│ ├── fibonacci_recursive(0) → 0
37+
├── fibonacci_recursive(3)
38+
├── fibonacci_recursive(2)
39+
│ ├── fibonacci_recursive(1) → 1
40+
│ ├── fibonacci_recursive(0) → 0
41+
├── fibonacci_recursive(1) → 1
42+
```
43+
As shown above, even for a small input like n = 5, the function makes redundant calculations, leading to an exponential growth in execution time.
44+
```python
45+
def fibonacci_recursive(n: int) -> int:
46+
"""Generates the Fibonacci sequence up to the nth term using recursion without memoization."""
47+
48+
# Handle negative inputs
49+
if n < 0:
50+
raise ValueError("Input must be a positive integer.")
51+
52+
# Base cases
53+
if n == 0:
54+
return 0
55+
if n == 1:
56+
return 1
57+
58+
# do the recursive calculation for the nth number
59+
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
60+
```
61+
It takes in integer as an input and outputs an integer which is the fibonacci number's answer. There are two base cases for this approach which the input integer, in this case "n", is equal to 0 and 1. Each function call branches into two recursive calls, forming a binary tree of depth n. This results in an exponential number of operations, making the approach extremely slow for large values of n. Therefore, the worst-time complexity is O(n^2)!
62+
2663

2764
### Generate Fibonacci using a Memoized approach
2865

0 commit comments

Comments
 (0)