1 public class TestRecursion01 { 2 3 public static void main(String[] args) { 4 long d1 = System.currentTimeMillis(); 5 System.out.printf("%d阶乘的结果:%s%n",10,factorial(10)); 6 long d2 = System.currentTimeMillis(); 7 System.out.printf("递归费时%s%n",d2-d1); 8 } 9 static long factorial(int n) { 10 if(n == 1) {//递归头 11 return 1; 12 }else {//递归体 13 return n*factorial(n-1); 14 } 15 //1*2*3*....*10 16 } 17 }
执行结果:
![](https://images2018.cnblogs.com/blog/1284500/201807/1284500-20180713143539078-234977270.png)
注意事项:
任何能用递归解决的问题,也能使用迭代解决。
在要求高性能的情况下,应尽量避免使用递归。递归既耗时又消耗内存。