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?
递归算法求数列代码,运行很久都没出来,有兴趣的可以试一下到底要多少时间:
非递归代码:
迭代器版本:
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
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
相关文章推荐
- Oracle web tier——oracle web cache
- ArcGIS Server 10.1新特性
- 【Qt】全局忽略编译警告
- MODIS NDVI数据处理相关问题
- 细心
- 花瓣网轮播图效果
- 2.6Bootstrap学习之工具class、响应式工具
- onSaveInstanceState
- LeetCode刷题笔录Climbing Stairs
- 20140503朗沃
- 二进制文件读写函数
- springMVC传对象参数
- 二进制文件读写函数
- QueryRunner
- Linux常用快捷键
- SGU 131-状压dp
- VMware 10安装CentOs 6.5
- 再发一个HTML5+WebSocket+PHP多进程 多人在线小蝌蚪游戏[强烈推荐]
- 复习PHP-语言参考-预定义接口
- jquery combox与combobox使用