Answer the question
In order to leave comments, you need to log in
Fibonacci number?
Coursera does not make a decision.
Condition of the problem:
Given a natural number A. Determine what Fibonacci number it is, that is, print a number n such that F[n]=A
If A is not a Fibonacci number, print the number -1
-1
Examples:
Test 1
Input : 8
Program output: 6
Test 2
Input: 10
Program output: -1
Test 3
Input: 13
Program output: 7
Can't find error
n = int(input())
f = 0
res = 1
f0 = 1
i = 0
while i < n:
res = f
f = f0 + f
f0 = res
i += 1
if n == f:
print(i)
break
if n < 0 or n != f:
print(-1)
elif n == 0:
print(0)
Answer the question
In order to leave comments, you need to log in
Here
Must be
A after the loop, check only n==0, and the second check is not needed, in all other cases, return -1.
but i like this one better
def get_fib_ind(n):
ind = 0
a, b = 0, 1
while b <= n:
ind += 1
a, b = b, a+b
if a == n:
return ind
return -1
print(
get_fib_ind(
int(input())
)
)
n is the number to be checked, i.e., according to condition A, which is entered by the user, and you compare it with the serial number i in the loop.
n needs to be compared with Fiebonacci numbers
If the number A=1 is taken as n=2 (although one is both the first and second number in the Fibonacci sequence), then:
a = int(input())
fib_1 = 0
fib_2 = 1
fib_summ = 1
n = 0
res = -1
while fib_1 <= a:
fib_summ = fib_1 + fib_2
fib_1 = fib_2
fib_2 = fib_summ
n += 1
if fib_1 == a:
res = n
elif a == 0:
res = 0
print(res)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question