Skip to content
6.G. While: Fibonacci index
Profile icon

"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.

Also had an easier way:

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)

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

Who knows where things went wrong?

You are viewing a single comment. View All
Profile icon

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: