您的位置:首页 > 其它

Problem 25:1000-digit Fibonacci number

2014-05-03 23:40 351 查看
题目描述:

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 first term in the Fibonacci sequence to contain 1000 digits?

递归算法求数列代码,运行很久都没出来,有兴趣的可以试一下到底要多少时间:

def fun(num):
return len(str(num))

def f(num):
if num==1 or num==2:
return 1
else:
return f(num-1)+f(num-2)
i=1
while(fun(f(i))<1000):
i+=1
print i


非递归代码:

def fun(num):
return len(str(num))
f1=1
f2=1
f3=2
count=3
while(fun(f3)<1000):
f1=f2
f2=f3
f3=f1+f2
count+=1
print count

迭代器版本:

class Fibs:
def __init__(self):
self.a=0
self.b=1

def next(self):
self.a,self.b=self.b,self.a+self.b
return self.a

def __iter__(self):
return self

def fun(num):
return len(str(num))

fibs=Fibs()
count=0
for fib in fibs:
count+=1
if fun(fib)>=1000:
break
print count
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: