奶牛问题

 1 public class Test {
 2     private static int sum=1;
 3     private static void giveBirth(int year)
 4     {
 5         if(year>3)
 6             sum+=year-3;
 7         for(year=year-3;year>0;year--)
 8         {
 9             giveBirth(year);
10         }
11     }
12     public static void main(String[] args)
13     {
14         System.out.println("please input years:");
15         Scanner scanner=new Scanner(System.in);
16         int year=Integer.parseInt(scanner.nextLine());
17         giveBirth(year);
18         System.out.println(sum);
19     }
20 }

 

 1     //对整个过程进行分析(不要从头开始分析),第n年的奶牛头数=第n-1年的奶牛头数+第n年新增的奶牛数
 2     //第n年新增的奶牛数=第n-1年大与三岁的牛的头数
 3     public static int func(int n)
 4     {
 5         if(n<=3)
 6         {
 7             return 1;
 8         }
 9         else {
10             return func(n-1)+func(n-3);
11         }
12     }
13     public static void main(String[] args) {
14         System.out.println(func(5));
15     }

 

posted @ 2015-04-28 19:13  Maydow  阅读(213)  评论(0编辑  收藏  举报