zoukankan      html  css  js  c++  java
  • 第一个算法

    【程序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秒长。

  • 相关阅读:
    Django -- 模板系统
    CSRF_TOKEN
    MySQL的sql_mode模式说明及设置
    程序员必备的600单词
    前端 -- jQuery
    datatime模块
    github高效搜索
    Mac上Homebrew常用命令总结
    对比System.currentTimeMillis()、new Date().getTime()、System.nanoTime()
    MACOS安装使用kafka
  • 原文地址:https://www.cnblogs.com/renyubins/p/3779116.html
Copyright © 2011-2022 走看看