古典問題:有多少對兔子

古典問題:有一對兔子,從出生後第3個月起每月都生一對兔子,小兔子長到第三個月後每月又生一對兔子,假如兔子都不死,問每月的兔子總數爲多少?code

分析:

month 1 2 3 4 5 6 7 8 9 10
total 1 1 2 3 5 8 13 21 34 55

此問題是Fibonacci數列問題, f(n) = f(n-1) + f(n-2)ci

解決舉例

package sloveproblems;

public class howmanyrabbits {

    public static void main(String[] args){
    int a = 0;
    int b = 1;
    for (int i=0; i<=9; i++){  //for ten month
        int c = a + b;
        a = b;
        b = c;
        int month = i+1;
        System.out.println("the " + month+"th rabbits are: " + a);
    }
    }
}
相關文章
相關標籤/搜索