设为首页 加入收藏

TOP

斐波那契数列 的三种实现方法
2018-12-19 02:55:37 】 浏览:66
Tags:那契 数列 实现 方法
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/copytop/article/details/60604326

很好奇兔子君到底有多流氓? 结果发现i7跑fib(200)的时间都可以泡杯茶了。惊讶,SO想试下多种解法

斐波那契数列 定义如下:

F(0) = 0,F(1)=1

F(n)=F(n-1)+F(n-2) (n≥2)


1.正向递推:

import time
#直接实现
def fibonacci1(n):
    t=0
    after=1
    for i in range(0,n):
        t,after=after,after+t
    return t

start=time.clock()
print fibonacci1(200)
end=time.clock()
print 'time of fibonacci1',end-start

2.递归(加入缓存):

import time
def fibonacci(n,d):#递归
    if n==0 :
        return  0
    if n==1:
        return  1
    else:
        if cache(n,d)!=-1:
            return cache(n,d)
        else:
            d[n]=fibonacci(n-1,d)+fibonacci(n-2,d)
            return  fibonacci(n-1,d)+fibonacci(n-2,d)

def cache(n,d):
    if n in d:
        return int(d[n])
    else:
        return -1

d={}
start=time.clock()
print fibonacci(200,d)
end=time.clock()
print 'time of fibonacci',end-start

3.通项公式 :
点击打开链接 推导步骤

import time
def best(n):
    t=5**0.5
    a=((t+1)/2)**n-((1-t)/2)**n
    a=a/t
    return a

start=time.clock()
print best(200)
end=time.clock()
print 'time of best',end-start

4.运行结果

280571172992510140037611932413038677189525
time of fibonacci 0.000887445364758
280571172992510140037611932413038677189525
time of fibonacci1 2.35444688609e-05
2.80571172993e+41
time of best 6.94259979233e-06

多次运行可以发现三种算法时间复杂度 :3<1<2


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python环境搭建遇到问题及解决方.. 下一篇Python中的装饰器和函数式

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目