How can i get nth fibonacci number ? i want to find it without use recursion.I write code like that but i want my program shows only nth number

Question:

my code:

fib1 = 1
fib2 = 1
n = int(input('N ='))
for i in range(2,n):
    c = fib1 + fib2
    fib1 = fib2
    fib2 = c
    print(c)

answer:

N =
>>> 10
2
3
5
8
13
21
34
55
Asked By: Luna X

||

Answers:

Don’t print at each iteration, only after all of them, after the loop

fib1, fib2, c = 1, 1, None
n = int(input('N ='))
for i in range(2, n):
    c = fib1 + fib2
    fib1 = fib2
    fib2 = c
print(c)
Answered By: azro

Without recursion, you can used the closed form of the Fibonacci sequence.

def fib(n):
    return int(((1 + 5 ** 0.5) / 2) ** n / 5 ** 0.5 + 0.5)

print(fib(10))

Running the program will yield in the console 55

Answered By: Khoi Nguyen
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.