斐波那契数列——兔子生兔子问题

题目

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

程序分析

兔子的规律为数列1,1,2,3,5,8,13,21….,也就是这个数等于后两个数之和:
n=(n-1)+(n-2)

方法1:

public class TestFBNQ {
    public static void main(String[] args) {

        System.out.println("fb = " + fb(12) );
    }

    public static int fb(int month){

        if (month==1||month==2){

            return 1;
        }
        int f1=1;//第一个月
        int f2=1;//第二个月
        int f3=0;//第三个月
        for (int i = 3; i <= month ; i++) {
            f3 = f1+f2;
            f1 = f2;
            f2 = f3;
        }
        return f3;
    }
}

方法2:

递归法

public class TestFBNQ {
    public static void main(String[] args) {

        System.out.println("dg = " + dg(12) );
    }
    /**
     * 递归
     * @param month
     * @return
     */
    public static int dg(int month){

        if (month==1||month==2){

            return 1;
        }
        return dg(month-1)+dg(month-2);
    }
}

两种方法对比还是递归比较简单

猜你喜欢

转载自blog.csdn.net/zyw0101/article/details/80542988