Loading

Java算法题:兔子问题

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

解题思路:

 1     public int exp(int month){
 2         if(month == 1 || month == 2){
 3             return 1;
 4         }else{
 5             return exp(month-1)+exp(month-2);
 6         }
 7     }
 8     @Test
 9     public void testExp(){
10         Formatter f = new Formatter(System.out);
11         for(int i = 1;i < 21;i++){
12             f.format("%-10s",exp(i)+" ");
13             if(i%5==0){
14                 f.format("%-10s\n",exp(i));
15             }
16         }
17     }

测试结果:

1         1         2         3         5         5         
8         13        21        34        55        55        
89        144       233       377       610       610       
987       1597      2584      4181      6765      6765  

 

posted @ 2015-10-25 12:40  JamKong  阅读(814)  评论(0编辑  收藏  举报