Skip to content

Commit af16f1d

Browse files
authored
Update main.py
1 parent 064155c commit af16f1d

File tree

1 file changed

+30
-14
lines changed

1 file changed

+30
-14
lines changed

main.py

+30-14
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,3 @@
1-
def nth_fibonacci(n):
2-
3-
# Base case: if n is 0 or 1, return n
4-
if n <= 1:
5-
return n
6-
7-
# Recursive case: sum of the two preceding Fibonacci numbers
8-
return nth_fibonacci(n - 1) + nth_fibonacci(n - 2)
9-
10-
n = 5
11-
result = nth_fibonacci(n)
12-
print(result)
13-
14-
151
# Function to calculate the nth Fibonacci number using memoization
162
def nth_fibonacci_util(n, memo):
173

@@ -71,3 +57,33 @@ def nth_fibonacci(n):
7157
n = 5
7258
result = nth_fibonacci(n)
7359
print(result)
60+
61+
62+
def nth_fibonacci(n):
63+
if n <= 1:
64+
return n
65+
66+
# To store the curr Fibonacci number
67+
curr = 0
68+
69+
# To store the previous Fibonacci numbers
70+
prev1 = 1
71+
prev2 = 0
72+
73+
# Loop to calculate Fibonacci numbers from 2 to n
74+
for i in range(2, n + 1):
75+
76+
# Calculate the curr Fibonacci number
77+
curr = prev1 + prev2
78+
79+
# Update prev2 to the last Fibonacci number
80+
prev2 = prev1
81+
82+
# Update prev1 to the curr Fibonacci number
83+
prev1 = curr
84+
85+
return curr
86+
87+
n = 5
88+
result = nth_fibonacci(n)
89+
print(result)

0 commit comments

Comments
 (0)