zoukankan      html  css  js  c++  java
  • 菲波拉契数列

     1 /*
     2  * 古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,
     3  * 假如兔子都不死,问每个月的兔子总数为多少?   
     4 //这是一个菲波拉契数列问题
     5 

    6 */
        
    F(n) = {0,n=0; 1,n=0; F(n-1)+F(n-2),n>2 }


    方法一: 迭代实现
    public static void main(String[] args) { System.out.println("第1个月:" + 1); System.out.println("第2个月:" + 1); int M = 24; int f1 = 1,f2 = 1; int f; for(int i = 3;i <= M;i++){ f = f2; f2 = f1 + f2; f1 = f; System.out.println("第" + i + "个月:" + f2); } }

    方法二:数组迭代实现
    public static void main(String[] args) { int length = 40; int arr[] = new int[length]; arr[0] = 0; arr[1] = 1; for(int i=2; i<length; i++){ arr[i] = arr[i-1]+arr[i-2]; } for(int i=0;i<length;i++){ System.out.println(""+i+"个月: "+arr[i]); } }
    方法三:递归实现

    public
    static void main(String[] args) { for(int i=0;i<40;i++){ System.out.println(""+i+"个月: "+func(i)); } } public static int func(int i){ if(i<2){ return i==0 ? 0 : 1; }else{ return func(i-1)+func(i-2); } }
    def t(a,b):
        c = a + b
        print("%s",c)
        if c > 100:
            return
        t(b,c)
    
    if __name__ == "__main__":
        t(1,1)
    

      

  • 相关阅读:
    python 学习笔记(二)
    python list的简单应用
    linux命令--------系统自带vi/vim命令教程
    归并排序的时间复杂度分析
    webapplication发布
    安装windows phone 7
    部署webservice到远程服务器
    SQLserver2005描述对数据的调用
    11.python-过滤器(filter)
    10.python-映射函数(map)
  • 原文地址:https://www.cnblogs.com/wwzyy/p/5336867.html
Copyright © 2011-2022 走看看