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
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)
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
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
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)
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