如有bug,请多多原谅,麻烦评论区提醒,谢谢
package com.jdbk.www;
public class Testdigui {
public static void main(String[] args) {
a();
long t1 = System.currentTimeMillis();//开始时间
System.out.printf("%d的阶层结果是%n",10,factorial(10));
long t2 = System.currentTimeMillis();//结束时间
System.out.printf("递归时间%s%n",t2-t1);//计算耗时
factorialLoop(10);
}
static int count = 0;
static void a(){
System.out.println("a");
count++;
if(count<10){//递归头
a();//自己调用自己
}else{//递归体
return;
}
}
//计算10的阶层
static void b(){
System.out.println("b");
}
static long factorial(int n){
if(n==1){//递归头
return 1;
}else{//递归体
return n*factorial(n-1);
}
}
//测试普通循环费时与递归差距
static long factorialLoop(int a){
long t3 = System.currentTimeMillis();
long result = 1;
while(a>1){
result *= a*(a-1);
a -= 2;
}
long t4 = System.currentTimeMillis();
System.out.println(result);
System.out.printf("普通循环费时:%s%n",t4-t3);
return result;
}
}
对于一般的需求最好使用普通循环来做,不建议使用递归,毕竟递归十分的耗时