递归,汉诺塔,阶乘

 1 /**
 2  * 测试递归和迭代,汉诺塔,阶乘问题
 3  * @author 张涛
 4  *
 5  */
 6 
 7 import java.math.*;
 8 public class TestRecursion 
 9 {
10     public static void main(String[] args)
11     {
12         move(6,'A','B','C');
13         long d1 = System.currentTimeMillis();
14         System.out.printf("递归结果为%d
",factorial(15));
15         long d2 = System.currentTimeMillis();
16         System.out.printf("递归耗费时间为%d
",d2 - d1);
17         long d3 = System.currentTimeMillis();
18         System.out.printf("循环结果为%d
",circulation(15));
19         long d4 = System.currentTimeMillis();
20         System.out.printf("循环耗费时间为%d
",d4 - d3);
21     }
22     
23     //1.递归实现汉诺塔问题,A借助B全部到C
24     static void move(int n,char a,char b, char c)
25     {
26         if(n == 1)
27         {
28             System.out.printf("%c -> %c
",a,c);
29         }
30         else
31         {
32             move(n-1,a,c,b);//注意不能写成move(n-1,'A','C','B');
33             /**
34              * 额,我一开始犯的错误,理解不透彻
35              * 写成了move(n-1,'A','C','B');
36              * 以3举例
37                         n = 3: a ->A
38                                b ->B
39                                c ->C
40                            
41                         n = 2: a ->A
42                                b ->C
43                                c ->B
44              * 
45              * 但是如果这样写move(n-1,'A','C','B');每次都是把'A','B','C'给发过去了,
46              * 而不是a,b,c对应的柱子了
47              */
48             System.out.printf("%c -> %c
",a,c);
49             move(n-1,b,a,c);
50         }
51     }
52      //递归实现阶乘问题
53         static int factorial(int n)
54         {
55             if(n == 1)
56             {
57                 return 1;
58             }
59             else
60             { 
61                 return n * factorial(n - 1);
62             }
63         }
64     //循环实现阶乘问题
65         static int circulation(int n)
66         {
67             int m = 1;
68             while(n > 0)
69             {
70                 m *= n;
71                 n--;
72             }
73             return m;
74         }
75 }
原文地址:https://www.cnblogs.com/zhangqiling/p/11339870.html