Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added fibonacci [python] #877

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 44 additions & 12 deletions fibonacci_number/FibonacciNumber.py
Original file line number Diff line number Diff line change
@@ -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()