黑马程序员技术交流社区
标题:
兔子问题大总结
[打印本页]
作者:
小钟
时间:
2014-5-31 11:23
标题:
兔子问题大总结
public class Prog{
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = 20;
System.out.println("第"+n+"个月兔子总数为"+getTuZi (n));
System.out.println("第"+n+"个月兔子总数为"+getTuZi2 (n));
System.out.println("第"+n+"个月兔子总数为"+getTuZi3 (n));
System.out.println("第"+n+"个月兔子总数为"+getTuZi4 (n));
}
//递归方法;
public static int getTuZi(int month){
if(month==1 || month==2)
return 1;
else
return getTuZi(month-1)+getTuZi(month-2);
}
//数组算法;
public static int getTuZi2(int month){
int[] arr=new int[month];
for(int i=0;i<arr.length;i++){
if(i==0||i==1){
arr[i]=1;
}else{
arr[i]=arr[i-1]+arr[i-2];
}
}
return arr[month-1];
}
//保存前两个月的兔子对数;
public static int getTuZi3(int month){
int month1=1,month2=1,monthn;
for(int i=3;i<=month;i++){
monthn=month2;
month2=month2+month1;
month1=monthn;
}
return month2;
}
//函数调用;
public static int getTuZi4(int month) {
double rabSum = (1 / Math.sqrt(5))
* (Math.pow(((1 + Math.sqrt(5)) / 2), month) - Math.pow(
((1 - Math.sqrt(5)) / 2), month));
return (int) rabSum;
}
}
复制代码
作者:
heima_xyu
时间:
2014-5-31 12:16
兔子问题是指?
作者:
yang1352546
时间:
2014-5-31 14:36
这么全面。:handshake
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2