A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© yashiro 中级黑马   /  2016-2-28 22:20  /  1281 人查看  /  7 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

故事得从西元1202年说起,话说有一位意大利青年,名叫斐波那契。
* 在他的一部著作中提出了一个有趣的问题:假设一对刚出生的小兔一个月后就能长成大兔,再过一个月就能生下一对小兔,并且此后每个月都生一对小兔,一年内没有发生死亡,
* 问:一对刚出生的兔子,一年内繁殖成多少对兔子?
* 1 1 2 3 5 8 13
* 第一个月一对小兔子                                        1
* 第二个月一对大兔子                                        1
* 第三个月一对大兔子生了一对小兔子                2
* 第四个月一对大兔子生了一对小兔子
*                  一对小兔子长成大兔子                        3
* 第五个月两对大兔子生两对小兔子       
*                  一对小兔子长成大兔子                        5
public static void main(String[] args) {
                int num = fun(20);
                System.out.println(num);
        }
        public static int fun(int num) {
                if (num==1 || num==2) {
                        return 1;
                }else {
                        return fun(num-2) + fun(num-1);
                }
        }

7 个回复

倒序浏览
public class lianxi01 {
public static void main(String[] args) {
System.out.println("第1个月的兔子对数:    1");
System.out.println("第2个月的兔子对数:    1");
int f1 = 1, f2 = 1, f, M=24;
     for(int i=3; i<=M; i++) {
      f = f2;
      f2 = f1 + f2;
      f1 = f;
      System.out.println("第" + i +"个月的兔子对数: "+f2);
         }
}
}
回复 使用道具 举报
哇,好厉害啊
回复 使用道具 举报
public class Test5 {

        /**
         * * 不死神兔
        * 故事得从西元1202年说起,话说有一位意大利青年,名叫斐波那契。
        * 在他的一部著作中提出了一个有趣的问题:假设一对刚出生的小兔一个月后就能长成大兔,再过一个月就能生下一对小兔,并且此后每个月都生一对小兔,一年内没有发生死亡,
        * 问:一对刚出生的兔子,一年内繁殖成多少对兔子?
        * 1 1 2 3 5 8 13 21
        * 1 = fun(1)
        * 1 = fun(2)
        * 2 = fun(1) + fun(2)
        * 3 = fun(2) + fun(3)
         */
        public static void main(String[] args) {
                System.out.println(fun(8));
        }

        public static void demo1() {
                //用数组做不死神兔
                int[] arr = new int[8];
                //数组中第一个元素和第二个元素都为1
                arr[0] = 1;
                arr[1] = 1;
                //遍历数组对其他元素赋值
                for(int i = 2; i < arr.length; i++) {
                        arr[i] = arr[i - 2] + arr[i - 1];
                }
                //如何获取最后一个数
                System.out.println(arr[arr.length - 1]);
        }

        /*
         * 用递归求斐波那契数列
         */
        public static int fun(int num) {
                if(num == 1 || num == 2) {
                        return 1;
                }else {
                        return fun(num - 2) + fun(num - 1);
                }
        }
}
回复 使用道具 举报
厉害,都挺棒的
回复 使用道具 举报
赞赞一个!
回复 使用道具 举报
这个方法用递归的话资源浪费比较厉害
回复 使用道具 举报
都挺厉害的啊!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马