大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。
大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上(可以借助第三根柱子做缓冲)。
并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。
如图【1.jpg】是现代“山寨”版的该玩具。64个圆盘太多了,所以减为7个,
金刚石和黄金都以木头代替了…但道理是相同的。
据说完成大梵天的命令需要太多的移动次数,以至被认为完成之时就是世界末日!
你的任务是精确计算出到底需要移动多少次。
很明显,如果只有2个圆盘,需要移动3次。
圆盘数为3,则需要移动7次。
那么64个呢?
答案写在“解答.txt”中,不要写在这里!
*/
import java.math.BigDecimal;
public class llq1{
public static void hanio(int n,char a,char b,char c) {
if(n>0) {
hanio(n-1,a,c,b);
hanio(n-1,b,a,c);
s++;
}
}
static long s=0;
public static void main(String[] args) {
int n=10;
System.out.println("圆盘个数\t移动次数");
for(int i=1;i<=n;i++) {
s=0;
hanio(i,'a','b','c');
System.out.println(i+"->\t"+s);
}
System.out.println("由上找到规律:移动次数=2^n-1");
System.out.println("64个圆盘移动次数为\n");
BigDecimal bi=new BigDecimal("2");
bi=bi.pow(64).subtract(BigDecimal.ONE);
System.out.println(bi);
}
}
结果:
圆盘个数 移动次数
1-> 1
2-> 3
3-> 7
4-> 15
5-> 31
6-> 63
7-> 127
8-> 255
9-> 511
10-> 1023
由上找到规律:移动次数=2^n-1
64个圆盘移动次数为
18446744073709551615
补充:
public class llq1{
static int s=0;
public static void main(String[] args) {
hanio(3,'a','b','c');
System.out.print(s);
}
static void hanio(int n,char a,char b,char c) {
if(n>0) {hanio(n-1,a,c,b);
move(a,c);
hanio(n-1,b,a,c);
s++;}
}
static void move(char a,char b) {
System.out.println("move "+a+" to "+b);
}
}
结果:
move a to c
move a to b
move c to b
move a to c
move b to a
move b to c
move a to c
7