← Back to Community
##### 6.G. While: Fibonacci index
Profile icon
pole55

Statement
"Fibonacci numbers are the numbers in the integer sequence starting with 1, 1 where every number after the first two is the sum of the two preceding ones: 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

Given a positive integer, determine if it's the nth Fibonacci number for some n. If it is, print such n, otherwise print -1."

Example input: 8
Example output: 6

=============================

Have a problem with the digit 1134903170 (see the code below).
It is the 45th Fibonacci number, but the code did not work.

x = int(input())
lst = [1, 1]

for i in range(2, x+1):
--lst.append(lst[-1] + lst[-2])

if lst.count(x) >= 1:
--print(lst.index(x) + 1)
else:
--print(-1)

But the same problem with 1134903170 here.
The program took too long to execute.

Who knows where things went wrong?

Voters
Profile icon
Profile icon
projectthingy
Profile icon
ZiHanZhu2
Profile icon
sonnyujin
Profile icon
WilliamCaley
Profile icon
gbahia
Profile icon
a38268Joana
Profile icon
ankashate040
Profile icon
TrevorKlein
Profile icon
pole55
hotnewtop
Profile icon
darwin1012

prev = 1
next = 1
index = 2
check_fib = int(input())

while check_fib > next:
new_next = prev + next
prev = next
next = new_next
index += 1

if check_fib == next:
print(index)
else:
print(-1)

it says to use a while loop

Profile icon
ash15khng

There doesn't seem to be anything wrong with typing that number in?

Profile icon
pole55

@ash15khng the code gives -1 instead of 45. and the easier version does not calculate it, freezes, because calculations go very long.

Profile icon
jiuyuan3

try this:
prev, next = 1, 1
index = 2
possible_fib = int(input())
while possible_fib > next:
prev, next = next, prev + next
index += 1
if possible_fib == next:
print(index)
else:
print(-1)