zoukankan      html  css  js  c++  java
  • 求斐波那契数列第n个数的效率比较

    https://www.bilibili.com/video/BV1sX4y1G7oM?p=5&spm_id_from=pageDriver

    求斐波那契数列第n个数
    package testpack;
    
    /**
     * 求斐波那契数列第n个数
     */
    public class T1 {
        public static void main(String[] args) {
    //        System.out.println(fun1(60));
    //        System.out.println(fun2(60));
    
            int n = 76;
    //        TimeTool.check("fun1", new TimeTool.Task() {
    //            @Override
    //            public void execute() {
    //                System.out.println(fun1(n));//递归
    //            }
    //        });
    
            TimeTool.check("fun2", new TimeTool.Task() {
                @Override
                public void execute() {
                    System.out.println(fun2(n));//循环
                }
            });
        }
    
        /**
         * 递归实现
         * @param n
         * @return
         */
        public static long fun1(long n) {
            if (n <= 1) return n;
            return fun1(n - 1) + fun1(n - 2);
        }
    
        /**
         * 循环实现
         * @param n
         * @return
         */
        public static int fun2(int n) {
            if (n <= 1) return n;
            int first = 0;
            int second = 1;
            for (int i = 0; i < n - 1; i++) {
                int sum = first + second;
                first = second;
                second = sum;
            }
            return second;
        }
    }
    

      

    计时器类
    package testpack;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    /**
     * 计时器
     */
    public class TimeTool {
        private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
    
        public interface Task {
            void execute();
        }
    
        public static void check(String title, Task task) {
            if (task == null) {
                return;
            }
            title = (title == null) ? "" : ("[" + title + "]");
            System.out.println(title);
            System.out.println("开始:" + sdf.format(new Date()));
            long begin = System.currentTimeMillis();
            task.execute();
            long end = System.currentTimeMillis();
            System.out.println("结束:" + sdf.format(new Date()));
            double time = (end - begin) / 1000.0;
            System.out.println("耗时:" + time + "秒");
            System.out.println("-------------------");
        }
    }
    

      

    https://github.com/godmaybelieve
  • 相关阅读:
    【BZOJ1046】[HAOI2007]上升序列
    【BZOJ1045】[HAOI2008]糖果传递
    【BZOJ1044】[HAOI2008]木棍分割
    【BZOJ1041】[HAOI2008]圆上的整点
    【LG2257】YY的GCD
    【BZOJ1018】[SHOI2008]堵塞的交通
    【LG4735】最大异或和
    【POJ2182】Lost Cows
    【POJ2482】Stars in Your Window
    【POJ1733】Parity game
  • 原文地址:https://www.cnblogs.com/yuyu666/p/15045587.html
Copyright © 2011-2022 走看看