zoukankan      html  css  js  c++  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));
        }
    }
  • 相关阅读:
    记第一场省选
    POJ 2083 Fractal 分形
    CodeForces 605A Sorting Railway Cars 思维
    FZU 1896 神奇的魔法数 dp
    FZU 1893 内存管理 模拟
    FZU 1894 志愿者选拔 单调队列
    FZU 1920 Left Mouse Button 简单搜索
    FZU 2086 餐厅点餐
    poj 2299 Ultra-QuickSort 逆序对模版题
    COMP9313 week4a MapReduce
  • 原文地址:https://www.cnblogs.com/chenyanbin/p/12174169.html
Copyright © 2011-2022 走看看