背景资料:
汉诺塔:汉诺塔(又称河内塔)问题是源于印度一个古老传说的益智玩具。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘。大梵天命令婆罗门把圆盘从下面开始按大小顺序重新摆放在另一根柱子上。并且规定,在小圆盘上不能放大圆盘,在三根柱子之间一次只能移动一个圆盘。
本程序所要解决的是: 计算N(N=<64)个圆盘组成的塔,所要移动的次数。
数学算法是:对于N个圆盘组成的塔计算公式:
设移动次数为H(n)
H(n=2^n-1;
实现代码:
#include "stdafx.h"
#include<iostream>
#include <string>
#include<conio.h>
using namespace std;
class TowerBrahma{
private:
unsigned int layer;
unsigned long double times;
public:
TowerBrahma():layer(0),times(0){}
void SetLayer(const unsigned int setlay);
void CountFun(void);
void printResult(void);
};
void TowerBrahma::SetLayer(const unsigned int setlay)
{
layer=setlay;
}
void TowerBrahma::CountFun(void)
{
if(layer>0)
{
times=1;
for(;layer!=0;layer--)
times*=2;
times-=1;
}
else
times=0;
}
void TowerBrahma::printResult(void)
{
cout<<"The calculation results: "<<times<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
unsigned int n=1;
TowerBrahma tower;
cout<<"Please input layers of tower (layer=<64) "<<endl;
cout<<"Please input 65 for /Exit the calculation "<<endl;
while(cin>>n)
{
if(n>64)
{
if(n==65)
{
cout<<"Exit Successfully! "<<endl;
break;//Exit the calculation
}
cout<<"Note:the number is too large! "<<endl;
cout<<"Please input number=<64 "<<endl;
continue ;
}
tower.SetLayer(n);
tower.CountFun();
tower.printResult();
}
if(!cin)
cout<<"Error input!"<<endl;
_getch();
return 0;
}