zoukankan      html  css  js  c++  java
  • java基础---------递归和循环的使用效率

    package java基础;

    /**
    * 参数递归和迭代的效率,递归效率太低,如果用到递归一般使用循环
    */

    public class TestRecursion {
    public static void main(String[] args) {
         //标记递归方法开始执行事件
    long d1=System.currentTimeMillis();
    System.out.printf("%d阶乘结果:%s%n",10,factorial(10));
          //递归程序结束时间
    long d2=System.currentTimeMillis();
    System.out.printf("递归耗时:%s%n",d2-d1);//计算出递归使用的时间
    factorialLoop(10);
    }

    //计算阶乘方法,递归就是方法自己调用自己
    static long factorial(int a){

    if(a==1){
    return 1;
    }
    else {
    return a*factorial(a-1);
    }
    }
    //高性能一般使用循环,递归效率太低
    static long factorialLoop(int b){
    long d3=System.currentTimeMillis();
    long result=1;
    while (b>1){
    result*=b*(b-1);
    b=b-2;
    }
    long d4=System.currentTimeMillis();
    System.out.println("循环阶乘结果"+result);
    System.out.printf("递归耗时:%s%n",d4-d3);
    return result;

    }
    }

    执行结果:

    10阶乘结果:3628800
    递归耗时:25
    循环阶乘结果3628800
    递归耗时:0

    
    
  • 相关阅读:
    html例题——简历
    求值
    c#语句实例(排大小)
    3.6语言基础笔记
    2016.3.5进制间的转换
    3.26-1
    3.23(网页)
    3.23
    3.22
    3.20
  • 原文地址:https://www.cnblogs.com/zzzao/p/10888102.html
Copyright © 2011-2022 走看看