A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 小钟 中级黑马   /  2014-5-31 11:23  /  762 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文


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

2 个回复

倒序浏览
兔子问题是指?
回复 使用道具 举报
这么全面。:handshake
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马