黑马程序员技术交流社区

标题: 兔子问题大总结 [打印本页]

作者: 小钟    时间: 2014-5-31 11:23
标题: 兔子问题大总结

  1. public class Prog{

  2.         public static void main(String[] args) {
  3.                 // TODO Auto-generated method stub
  4.                 int n = 20;
  5.                 System.out.println("第"+n+"个月兔子总数为"+getTuZi (n));
  6.                 System.out.println("第"+n+"个月兔子总数为"+getTuZi2 (n));
  7.                 System.out.println("第"+n+"个月兔子总数为"+getTuZi3 (n));
  8.                 System.out.println("第"+n+"个月兔子总数为"+getTuZi4 (n));
  9.         }
  10.        
  11.          //递归方法;
  12.                 public static int getTuZi(int month){
  13.                         if(month==1 || month==2)
  14.                            return 1;
  15.                         else
  16.                            return getTuZi(month-1)+getTuZi(month-2);
  17.                 }   
  18.             //数组算法;
  19.                 public static int getTuZi2(int month){
  20.                         int[] arr=new int[month];
  21.                         for(int i=0;i<arr.length;i++){
  22.                                 if(i==0||i==1){
  23.                                         arr[i]=1;
  24.                                 }else{
  25.                                         arr[i]=arr[i-1]+arr[i-2];
  26.                                 }
  27.                         }
  28.                         return arr[month-1];
  29.                 }
  30.             //保存前两个月的兔子对数;
  31.                 public static int getTuZi3(int month){
  32.                         int month1=1,month2=1,monthn;
  33.                         for(int i=3;i<=month;i++){
  34.                                 monthn=month2;
  35.                                 month2=month2+month1;
  36.                                 month1=monthn;
  37.                         }
  38.                         return month2;
  39.                 }
  40.             //函数调用;
  41.             public static int getTuZi4(int month) {
  42.                         double rabSum = (1 / Math.sqrt(5))
  43.                                         * (Math.pow(((1 + Math.sqrt(5)) / 2), month) - Math.pow(
  44.                                                         ((1 - Math.sqrt(5)) / 2), month));
  45.                         return (int) rabSum;
  46.                 }

  47. }
复制代码

作者: heima_xyu    时间: 2014-5-31 12:16
兔子问题是指?
作者: yang1352546    时间: 2014-5-31 14:36
这么全面。:handshake




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2