Java代码实现斐波那契数列

 

斐波那契数列

百度百科

代码演示

二种算法执行效率示例

  运行结果可知,算法不同,结果相同,代码运行效率具有天壤之别。一个好的算法,可以让程序运行效率大幅度提升~

代码拷贝区

package com.cyb;
/**
 * 斐波那契数列:后一个数等于前两个数之和 0 1 1 2 3 5 8 13 21.....
 * @author chenyanbin
 *
 */
public class Main {
    /*
     * 递归方式
     */
    public static int fib1(int n) {
        if (n <= 1)
            return n;
        return fib1(n - 1) + fib1(n - 2);
    }
    /*
     * 优化后算法
     */
    public static int fib2(int n) {
        if (n <= 1) //第一个、第二个数,返回本身
            return n;
        int first = 0;
        int second = 1;
        while (n-- > 1) {
            second += first; // 第三个数=第一个数+第二个数
            first = second - first;
        }
        return second;
    }
    public static void main(String[] args) {
        Long begin = System.currentTimeMillis();
        System.out.println(fib1(40));
        Long end = System.currentTimeMillis();
        System.out.println("递归算法;开始时间:" + begin + ";结束时间:" + end + ";耗时:" + (end - begin));
        //-------------
        Long begin2 = System.currentTimeMillis();
        System.out.println(fib2(40));
        Long end2 = System.currentTimeMillis();
        System.out.println("优化后算法;开始时间:" + begin2 + ";结束时间:" + end2 + ";耗时:" + (end2 - begin2));
    }
}

猜你喜欢

转载自www.cnblogs.com/chenyanbin/p/12174169.html
今日推荐