蓝桥杯 汉诺塔问题 64个圆盘的移动次数 ------------ BigInteger的应用

本文介绍了汉诺塔问题中64个圆盘移动的次数计算,通过公式H(n) = 2^n - 1得出2^64的值超出了long类型范围,因此使用BigInteger进行存储。示例代码展示了如何利用BigInteger进行幂运算、减法以及其他基本操作,如加、减、乘、除、取余、绝对值和比较大小,为处理大整数提供解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

汉诺塔问题的移动次数可以用H(n) = 2^n - 1来表示 

由于2^64次方超出了long的表示范围,所以用BigInteger 来存储这个大整数,代码如下:

public class C_1_27 {
    
    public static void main(String[] args) {
      
        System.out.println(BigInteger.valueOf(2).pow(64).subtract(BigInteger.valueOf(1)).toString());

    }

对于BigInteger用法的扩展如下:

 

//从键盘输入BigInteger类型数据
        Scanner sc = new Scanner(System.in);
        BigInteger bi = sc.nextBigInteger();
        //直接获取 valueOf(),x=2,y=1
        BigInteger x = BigInteger.valueOf(2);
        BigInteger y = BigInteger.valueOf(1);
        
        //2的64次方 pow()
        BigInteger pow=x.pow(64);
        
        //subtract() 减法:x-y:x.subtract(y)
        BigInteger re1 = x.subtract(y);
        //加乘除
        BigInteger re2 = x.add(y);
        BigInteger re3 = x.multiply(y);
        BigInteger re4 = x.divide(y);
        //mod()和remainder()都是取余
        BigInteger re5 = x.mod(y);
        BigInteger re7 = x.remainder(y);
        System.out.println(re5+" "+re7);
        //abs()绝对值
        BigInteger re6 = x.abs();
        
        //toString()将BigInteger 变成字符串序列
        String re = re1.toString();
        
        //比较大小x.compareTo(y)   ==0 相等;<0 x小于y ; >0 x大于y
        if (x.compareTo(y) == 0) {
            System.out.println("x与y相等");
        }else if (x.compareTo(y) < 0) {
            System.out.println("x小于y");
        }else if (x.compareTo(y) > 0) {
            System.out.println("x大于y");
        }
       

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值