zoukankan      html  css  js  c++  java
  • python计算斐波那契数列

    斐波那契数列就是黄金分割数列

    第一项加第二项等于第三项,以此类推

    第二项加第三项等于第四项

    代码如下

    这一段代码实现fib(n)函数返回第n项,PrintFN(m,n,i)函数实现输出第i项斐波那契数列,输出在m到n之间的斐波那契数的数量

    def fib(n) :
        x = 0
        x1 = 1
        x2 = 1
        i = 2
        while i <= n :
            i = i + 1
            x =x1 + x2
            x1 = x2
            x2 = x
        if (n == 1 or n == 2) :
            x = 1
        return x

    def PrintFN(m,n,i):
        c = i
        index = 0
        while fib(i) < 10000 :
            i = i + 1
        count = i
        i = 1
        while i < count :
            i = i + 1
            if fib(i) >= m and fib(i) <= n :
                index = index + 1
        v = fib(c)
        v = str(v)
        c = str(c)
        print("fib(" + c + ")" + "=" + v)
        print(index)

    m,n,i=input().split()
    n=int(n)
    m=int(m)
    i=int(i)
    PrintFN(m,n,i)

    另一段代码如下

    这一段代码实现fib(n)函数返回第n项,PrintFN(m,n,i)函数实现输出在m到n之间的所有的斐波那契数

    如果没有,显示No Fibonacci number

    def fib(n) :
        x = 0
        x1 = 1
        x2 = 1
        i = 2
        while i <= n :
            i = i + 1
            x =x1 + x2
            x1 = x2
            x2 = x
        if (n == 1 or n == 2) :
            x = 1
        return x

    def PrintFN(m,n,i):
        index = 0
        flag = 0
        while fib(i) < 10000 :
            i = i + 1
        count = i
        i = 1
        while i < count :
            i = i + 1
            if fib(i) >= m and fib(i) <= n :
                flag  = 1
                index = index + 1
                if index == 1 :
                    print(fib(i))
                    continue
                print(fib(i))
        if (flag == 0) :
            print("No Fibonacci number")

    m,n,i=input().split()
    n=int(n)
    m=int(m)
    i=int(i)
    PrintFN(m,n,i)

  • 相关阅读:
    TypeScript 源码详细解读(3)词法2-标记解析
    TypeScript 源码详细解读(2)词法1-字符处理
    TypeScript 源码详细解读(1)总览
    7年编程语言设计精华总结——写给想创造或正在创造一门新编程语言的同学
    我为什么开发新语言
    CLR值类型和引用类型
    运行时内存模型
    IronPython之基本类型
    .NET 应用程序域?
    .NET程序如何启动?
  • 原文地址:https://www.cnblogs.com/liuzhaowei/p/10767328.html
Copyright © 2011-2022 走看看