求斐波那契数列第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("-------------------");
    }
}

  

posted @ 2021-07-22 18:34  尐鱼儿  阅读(55)  评论(0编辑  收藏  举报