|
| 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 | + |
| 15 | +# Function to calculate the nth Fibonacci number using memoization |
| 16 | +def nth_fibonacci_util(n, memo): |
| 17 | + |
| 18 | + # Base case: if n is 0 or 1, return n |
| 19 | + if n <= 1: |
| 20 | + return n |
| 21 | + |
| 22 | + # Check if the result is already in the memo table |
| 23 | + if memo[n] != -1: |
| 24 | + return memo[n] |
| 25 | + |
| 26 | + # Recursive case: calculate Fibonacci number |
| 27 | + # and store it in memo |
| 28 | + memo[n] = nth_fibonacci_util(n - 1, memo) + nth_fibonacci_util(n - 2, memo) |
| 29 | + |
| 30 | + return memo[n] |
| 31 | + |
| 32 | + |
| 33 | +# Wrapper function that handles both initialization |
| 34 | +# and Fibonacci calculation |
| 35 | +def nth_fibonacci(n): |
| 36 | + |
| 37 | + # Create a memoization table and initialize with -1 |
| 38 | + memo = [-1] * (n + 1) |
| 39 | + |
| 40 | + # Call the utility function |
| 41 | + return nth_fibonacci_util(n, memo) |
| 42 | + |
| 43 | + |
| 44 | +if __name__ == "__main__": |
| 45 | + n = 5 |
| 46 | + result = nth_fibonacci(n) |
| 47 | + print(result) |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | +def nth_fibonacci(n): |
| 52 | + |
| 53 | + # Handle the edge cases |
| 54 | + if n <= 1: |
| 55 | + return n |
| 56 | + |
| 57 | + # Create a list to store Fibonacci numbers |
| 58 | + dp = [0] * (n + 1) |
| 59 | + |
| 60 | + # Initialize the first two Fibonacci numbers |
| 61 | + dp[0] = 0 |
| 62 | + dp[1] = 1 |
| 63 | + |
| 64 | + # Fill the list iteratively |
| 65 | + for i in range(2, n + 1): |
| 66 | + dp[i] = dp[i - 1] + dp[i - 2] |
| 67 | + |
| 68 | + # Return the nth Fibonacci number |
| 69 | + return dp[n] |
| 70 | + |
| 71 | +n = 5 |
| 72 | +result = nth_fibonacci(n) |
| 73 | +print(result) |
0 commit comments