The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
解题思路:题目给出了一个斐波那契数列,要求求出第一个位数达到1000位的数的索引:
程序是这样的:
f = {}
f[0] = 1
f[1] = 1
for n in range(2,100000,1):
f[n] = f[n - 1] + f[n - 2]
s = str(f[n])
numlist = [int(s[item: item + 1]) for item in range(0, len(s), 1)]
if len(numlist) < 1000:
print(n+2)
"""
思路:
定义f[0],f[1]
第3个数等于第1个加第2个的和
将结果转换为字符
将字符转换为N个组
统计共有多少位
小于1000位的F[n]加上2(f[0]和f[1])就是要求的f[n]
"""