题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
1.程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21....
package org.llh.demo01; import java.util.ArrayList; public class DemoTest002 { static ArrayList<Integer> list = new ArrayList(); int number ;//计算后一个月的兔子数量 public static void main(String[] args){ DemoTest002 st = new DemoTest002(); st.fun(); st.out(); } private void fun(){ //将12个月的兔子数量保存进list链表集合内 list.add(1); list.add(1); //前两个月的兔子数量 for(int i = 3;i<=12;i++){ number = list.get(i-2)+list.get(i-3); list.add(number); } } private void out(){//输出12个月的兔子数量 int i =1; for(int j:list){ System.out.println("第"+(i++)+"个月的兔子数量是"+j); } } }
12个月总数
package org.llh.demo01; public class DemoTest001 { static int MONTH[] = {1,2,3,4,5,6,7,8,9,10,11,12}; //第几个月 static int TYPE = 1; //一对生几对 private int getCount(int month, int type){ int sum = 0; if(month == 1 || month ==2){ sum = 1; }else{ sum = getCount(month - 1,1) + getCount(month - 2,1)*type; } return sum; } public static void main(String[] args) { int count=0; for(int a:MONTH){ int sum = (new DemoTest001()).getCount(a, TYPE); count = sum+count; } System.out.println(count); } }