File tree Expand file tree Collapse file tree 1 file changed +30
-14
lines changed
Expand file tree Collapse file tree 1 file changed +30
-14
lines changed Original file line number Diff line number Diff line change 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
162def nth_fibonacci_util (n , memo ):
173
@@ -71,3 +57,33 @@ def nth_fibonacci(n):
7157n = 5
7258result = nth_fibonacci (n )
7359print (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 )
You can’t perform that action at this time.
0 commit comments