递归算法——农夫养牛

 1 /**
 2  * Created by Administrator on 14-5-13.
 3  * 一个农夫养了一头牛,三年后,这头牛每年会生出1头牛,
 4  * 生出来的牛三年后,又可以每年生出一头牛……问农夫10年后有多少头牛?n年呢?
 5  */
 6 public class NewCow {
 7     public static void main(String[] args){
 8         for(int i=1;i<30;i++)
 9         {
10             System.out.print(i+"年后有牛:");
11             System.out.println(countCow(i));
12         }
13     }
14     public static int  countCow(int temp){
15         if(temp<=2)
16             return 1;
17         if(temp==3)
18             return 2;
19         else
20             return countCow(temp-1)+countCow(temp-3);
21     }
22 }

 

posted @ 2014-07-14 09:52  冥草有心  阅读(442)  评论(0编辑  收藏  举报