河内塔数学题

背景资料:

        汉诺塔:汉诺塔(又称河内塔)问题是源于印度一个古老传说的益智玩具。大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值