Fibonacci is an algorithm that forms numbers in a pattern to represent growth. The method sums the last two digits to produce the next integer in the sequence. It can be solved both recursively and iterative.

Iterative - Last Digit Fibonacci Number

``````#Fibonacci Last Digit

def new_fib(n):
#the_array = []
last_number = 0
current_number = 1

if n <= 1:
return n

#just store the last digit
for i in range(n-1):

fib = last_number + current_number # 0+1 = 1
last_number = current_number # lastnumber = 1(current = 1)
current_number = fib % 10
#the_array.append(fib)
# add fib = fib + current (fib = 1, current)

return current_number

n = int(input())
print(new_fib(n))
``````

Iterative - Using an Array to store numbers - This however, will take up a lot of memory on larger numbers. You can remove the array, and it will work the same.

``````#fibonacci non-recursive

def new_fib(n):
the_array = []
last_number = 0
current_number = 1

if n <= 1:
return n

for i in range(n-1):

fib = last_number + current_number # 0+1 = 1
last_number = current_number # lastnumber = 1(current = 1)
current_number = fib
the_array.append(fib)
# add fib = fib + current (fib = 1, current)

return current_number

n = int(input())
print(new_fib(n))
``````

Recursive

``````def fib_recur(n):
if (n <= 1):
return n

return fib_recur(n - 1) + fib_recur(n - 2)

n = int(input())
print(fib_recur(n))
``````