Given an integer a, determine its index among the Fibonacci numbers. Print the number n such that ϕn=a. If a is not a Fibonacci number, print -1.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
a = int(input()) if a == 0: print(0) elif a == 1: print(1) else: fib_0 = 0 fib_1 = 1 index = 1 while fib_1 < a: fib_n = fib_0 + fib_1 fib_0 = fib_1 fib_1 = fib_n index += 1 if fib_1 == a: print(index) else: print(-1) |
Explanation of the Code
- Reading Input:
- The
input()
function reads a line of text from the user.
- The
int()
function converts this input to an integer and stores it in the variable a
.
- Handling Base Cases:
if a == 0:
print(0)
elif a == 1:
print(1)
- If aaa is 0, print 0.
- If aaa is 1, print 1.
- Calculating Fibonacci Number and Its Index:
else:
fib_0 = 0
fib_1 = 1
index = 1
while fib_1 < a:
fib_n = fib_0 + fib_1
fib_0 = fib_1
fib_1 = fib_n
index += 1
if fib_1 == a:
print(index)
else:
print(-1)
- Initialize
fib_0
to 0 and fib_1
to 1.
- Initialize
index
to 1.
- Use a
while
loop to iterate and generate Fibonacci numbers until fib_1
is greater than or equal to aaa.
- In each iteration, calculate the next Fibonacci number (
fib_n
) as the sum of the previous two Fibonacci numbers.
- Update
fib_0
to the value of fib_1
and fib_1
to the value of fib_n
.
- Increment
index
by 1.
- After the loop, if
fib_1
equals aaa, print the value of index
. Otherwise, print -1.