Reputation: 35
I'm trying to solve this problem:
The 12th term, F12, is the first term to contain three digits.
What is the first term in the Fibonacci sequence to contain 1000 digits?
check = True
mylst = [1,1]
i = 1
while check:
if len(str(mylst[i])) >= 1000:
check = False
else:
mylst.append(mylst[i-1] + mylst[i-2])
i=i+1
a =str((mylst[len(mylst)-1]))
print(len(a))
print(a)
I seem to get correct answer for test cases 2 and 3 but my answer is not being accepted. Please help me me I am not able to understand what went wrong.
Upvotes: 1
Views: 344
Reputation: 649
I think you have an error in your code. If you look at the first iteration, you start with i=1 then call
mylst.append(mylst[i-1] + mylst[i-2])
Which will add mylst[0] + mylst[-1]
. This also gives me incorrect answers (for finding the first index with 3 digits, F12. Your code gives me F18).
Obviously this is not what you want to do. You can fix it by changing the list indices you are adding together.
check = True
mylst = [1,1]
i = 1
while check:
if len(str(mylst[i])) >= 1000:
check = False
else:
mylst.append(mylst[i] + mylst[i-1])
i=i+1
Then, as others have mentioned, you want the index of the answer.
print len(mylst)
Upvotes: 1
Reputation: 7821
Because the question is what term is the first to contain 1000 digits, not which number. So, if the question was
What is the first term in the Fibonacci sequence to contain 3 digits?
The answer would have been 12, not 144.
A general tip on Project Euler: Read the problem description carefully. And do it at least 3 times. If I had burned one calorie for each minute I've spent troubleshooting a PE problem due to a misread of the problem text, my body would probably be in a healthy shape.
Upvotes: 1
Reputation: 362657
The answer is the index of the fibonacci number, not the number itself.
So, if Fn is the first term in the Fibonacci sequence to contain 1000 digits you need to enter the corresponding n.
Upvotes: 1