diff --git a/main.py b/main.py index 9c5fb5d..9df2350 100644 --- a/main.py +++ b/main.py @@ -1,17 +1,3 @@ -def nth_fibonacci(n): - - # Base case: if n is 0 or 1, return n - if n <= 1: - return n - - # Recursive case: sum of the two preceding Fibonacci numbers - return nth_fibonacci(n - 1) + nth_fibonacci(n - 2) - -n = 5 -result = nth_fibonacci(n) -print(result) - - # Function to calculate the nth Fibonacci number using memoization def nth_fibonacci_util(n, memo): @@ -71,3 +57,34 @@ def nth_fibonacci(n): n = 5 result = nth_fibonacci(n) print(result) + + +def nth_fibonacci(n): + if n <= 1: + return n + + # To store the curr Fibonacci number + curr = 0 + + # To store the previous Fibonacci numbers + prev1 = 1 + prev2 = 0 + + # Loop to calculate Fibonacci numbers from 2 to n + for i in range(2, n + 1): + + # Calculate the curr Fibonacci number + curr = prev1 + prev2 + + # Update prev2 to the last Fibonacci number + prev2 = prev1 + + # Update prev1 to the curr Fibonacci number + prev1 = curr + + return curr + +n = 5 +result = nth_fibonacci(n) +print(result) + diff --git a/test.py b/test.py new file mode 100644 index 0000000..b0bf757 --- /dev/null +++ b/test.py @@ -0,0 +1,3 @@ + + +# hello world