兔子来了

题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
第一个月:1
第二个月:1
第三个月:2
第四个月:3
第五个月:5
第六个月:8
第七个月:13
...

规律: n(第n个月) = n-2 + n-1
从第三个月开始,当月的兔子数是之前两个月的和

public class RabbitCount{
    public static void main(String[] args){
        long month = Long.parseLong(args[0]);
        long final_count = 0;
        long month_1 = 1l;
        long month_2 = 1l;
        // 第一个月和第二个月兔子格式都是1,直接return
        if(month == 1 || month == 2){
            final_count = month_1;
            sys(month, final_count);
            return;
        }

        /**
         * final_count 最为最终的输出结果
         * 在改变 上个月个数-mouth_2 之前,需要将它记录下来
         * 之后将 temp 赋值给 mouth_1
         * 最后 final_count = month_2 + month_1
         */
        for(long i=3; i<month; i++){
            long temp = month_2;
            month_2 = month_1 + month_2;
            month_1 = temp;
            final_count = month_2 + month_1;
            sys(month, final_count);
        }
    }

    public static void sys(long month, long count){
        System.out.println("第 "+month+" 月,兔子的总数是: "+count);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值