- 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;
- }
- }
复制代码 |
|