• 尾部调用


    在阮一峰大侠的ECMAScript 6 入门

    了解到“尾递归”概念,一旦使用递归,就最好使用尾递归,再也不用担心"栈溢出"(stack overflow)。

    public class BeanInfoDemo {
        public static void main(String[] args) {
            Fibonacci(50);
        }
    
        private static void Fibonacci(int n) {
            long t1 = System.currentTimeMillis();
            System.out.println("传统:" + FibonacciC(n));
            long t2 = System.currentTimeMillis();
            System.out.println("传统耗时:" + (t2 - t1));
            System.out.println("尾部:" + FibonacciNew(n, 1, 1));
            long t3 = System.currentTimeMillis();
            System.out.println("尾部耗时:" + (t3 - t2));
        }
    
        public static long FibonacciC(long n) {
            if (n <= 2) {
                return 1;
            }
            return FibonacciC(n - 1) + FibonacciC(n - 2);
        }
    
        public static long FibonacciNew(long n, long ac1, long ac2) {
            if (n <= 2) {
                return ac2;
            }
            return FibonacciNew(n - 1, ac2, ac1 + ac2);
        }
    
    }

    结果为:

    传统:12586269025
    传统耗时:30040
    尾部:12586269025
    尾部耗时:0

     参考:http://www.ruanyifeng.com/blog/2015/04/tail-call.html

  • 相关阅读:
    iftop 安装流程
    Centos 6.5 Tengine 安装流程
    linux 查看系统进程前十
    Centos 6.5 mongodb 安装流程
    linux 磁盘查看方式
    Linux 磁盘分区及挂载
    linux 路由添加
    rsyslog 重启
    文件上传到Web服务器
    一些链接1
  • 原文地址:https://www.cnblogs.com/g120/p/12208730.html
Copyright © 2020-2023  润新知