算法---斐波那契数列问题

问题:

有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子对数为多少?

分析:

第1个月----1对兔子    x1 = 1
第2个月----1对兔子    x2 = x1 = 1
第3个月----2对兔子    x3 = x2 + x1
第4个月----3对兔子    x4 = x3 + x2
第5个月----5对兔子    x5 = x4 + x3
第6个月----8对兔子    x6 = x5 + x4
.......
类推得出规律,当月出生的兔子等于前两月出生的兔子的总和。

代码实现

方式一:递归

    public static void main(String[] args) {
        int month;
        while (true) {
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入月份:");
            month = sc.nextInt();
            System.out.println("第" + month + "月兔子对数为:" + recursive(month));
        }
    }

    //递归方式
    public static int recursive(int month){
        if (month <= 0) {//月份为0或负数
            return -1;
        } else if (month > 0 && month < 3) {//月份为 1、2
            return 1;
        } else {//月份大于3,递归:f(n) = f(n-1) + fn(n-2);
            return recursive(month - 1) + recursive(month - 2);
        }
    }

方式二:循环(采用中间变量)

    public static void main(String[] args) {
        int month;
        while (true) {
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入月份:");
            month = sc.nextInt();
            System.out.println("第" + month + "月兔子对数为:" + cycle(month));
        }
    }

    //循环方式
    public static int cycle(int month){
        //月为0或负数
        if (month <= 0) {
            return -1;
        }
        int number = 1;//初始本月兔子对数
        int temp1 = 1;//1月兔子对数
        int temp2 = 1;//2月兔子对数
        for (int i = 1; i <= month; i++) {
            if (i < 3) {//月为 1、2
                number = 1;
            } else if (i == month) {
                number = temp2 + temp1;//当月出生的兔子等于前两月出生的兔子的总和
            } else {
                number = temp2 + temp1;//当月出生的兔子等于前两月出生的兔子的总和
                temp1 = temp2;//将上月的兔子对数赋值给上上月
                temp2 = number;//将本月兔子对数赋值给上月
            }
        }
        return number;
    }

两种方式联合测试结果

猜你喜欢

转载自blog.csdn.net/zhuzbYR/article/details/102935466