第一个算法

【程序1】   题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第四个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子有多少对?

算法一:

public class ArithmeticTest1 {
    public static void main(String[] args){
        int[] count= new int[1000];long start=System.currentTimeMillis();
        for(i=1;i<=1000;i++) {
            if (i == 1 || i == 2) {
                System.out.println(i + ":" + 1);
                count[i]=1;
            }else{
               count[i]=count[i-1]+count[i-2];
                System.out.println(i + ":" + count[i]);
            }
        }
        long end=System.currentTimeMillis();
        System.out.println("运行时间:"+(end-start));
    }
}

执行时间在42ms左右。

算法二:

public class ArithmeticTest1 {
    public static void main(String[] args){
       ArrayList<Integer> count1=new ArrayList<Integer>();
        int i=0;
        long start=System.currentTimeMillis();
        for(i=1;i<=1000;i++) {
            if (i == 1 || i == 2) {
                System.out.println(i + ":" + 1);
                count1.add(1);
            }else{ 
                count1.add(count1.get(i-2)+count.get(i-3));
                System.out.println(i + ":" + count1.get(i-1));
            }
        }
        long end=System.currentTimeMillis();
        System.out.println("运行时间:"+(end-start));
}

执行时间约为44ms左右。

算法三:

public class ArithmeticTest1 {
    public static void main(String[] args){
        int i=0;
        long start=System.currentTimeMillis();
        math myMath = new math();
        for(i=1;i<=1000;i++)
            System.out.println(i + ":" + myMath.f(i));
        long end=System.currentTimeMillis();
        System.out.println("运行时间:"+(end-start));
    }
    static class math{
        public int f(int x){
            if(x==1||x==2)
                return 1;
            else
                return f(x-1)+f(x-2);
        }
    }
}

执行时间n秒长。

posted @ 2014-06-10 00:15  tranren  阅读(416)  评论(2编辑  收藏  举报