From 33a6f036833c7b7aa7b6230b46abc379774a99ff Mon Sep 17 00:00:00 2001 From: aayushi-0407 <12aaayushisingh@gmail.com> Date: Thu, 12 Oct 2023 18:19:47 +0530 Subject: [PATCH] Improved code and added iterative method for fibonacci --- fibonacci_number/FibonacciNumber.py | 56 ++++++++++++++++++++++------- 1 file changed, 44 insertions(+), 12 deletions(-) diff --git a/fibonacci_number/FibonacciNumber.py b/fibonacci_number/FibonacciNumber.py index 79b3bca0..e8343b16 100644 --- a/fibonacci_number/FibonacciNumber.py +++ b/fibonacci_number/FibonacciNumber.py @@ -1,20 +1,52 @@ -def fib(n): - if(n <= 1): +def recursive_fibonacci(n): + """ + Calculate the nth Fibonacci number using a recursive approach. + + :param n: The index of the Fibonacci number to calculate. + :return: The nth Fibonacci number. + """ + if n <= 1: return n else: - return fib(n-1) + fib(n-2) + return recursive_fibonacci(n - 1) + recursive_fibonacci(n - 2) + +def iterative_fibonacci(n): + """ + Calculate the nth Fibonacci number using an iterative approach. + + :param n: The index of the Fibonacci number to calculate. + :return: The nth Fibonacci number. + """ + previous_1 = 0 + previous_2 = 1 + + for i in range(n): + current = previous_1 + previous_2 + previous_1 = previous_2 + previous_2 = current + + return previous_1 def main(): - print("Enter the number :") - t = int(input()) - if(t == 0): - print("Enter correct number!") + """ + Main function to take user input and display the Fibonacci number. + """ + print("Choose a Fibonacci calculation method:") + print("1. Recursive") + print("2. Iterative") + + choice = int(input("Enter your choice (1 or 2): ")) + n = int(input("Enter the index of the Fibonacci number: ")) + + if n <= 0: + print("Please enter a valid index greater than zero.") else: - - for i in range(t): - x = fib(i) - print("fibonacci number is :") - print(x) + if choice == 1: + print("Fibonacci number at index", n, "is:", recursive_fibonacci(n)) + elif choice == 2: + print("Fibonacci number at index", n, "is:", iterative_fibonacci(n)) + else: + print("Invalid choice. Please select 1 or 2.") if __name__ == '__main__': main()