大整数Java幂计算期间的无限循环 [英] Infinite Loop During Calculation of Power of Big Integers Java

查看:64
本文介绍了大整数Java幂计算期间的无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在盯着这段代码,无法弄清楚它出了什么问题,也许换一双新的眼睛会有所帮助.

I have been staring at this code and cannot figure out what is wrong with it, maybe a fresh pair of eyes could help.

public static BigInteger powerOfBigInteger (BigInteger base, BigInteger power){
    if (power == BigInteger.valueOf(0)){
        return BigInteger.valueOf(1);
    }

    if (power == BigInteger.valueOf(1)){
        return base;
    }

    BigInteger x = BigInteger.valueOf(1);
    while (x != power ){
        base.multiply(base);
        x.add(BigInteger.valueOf(1));
        System.out.println(x + " " + power);
                   return base;
    } 

    return base;

我运行此命令,显然x从不等于幂.感谢您的帮助.

I run this and apparently x never equals power. Any help is appreciated.

推荐答案

您应该这样做

if (BigInteger.ZERO.equals(power)) return BigInteger.ONE;
if (BigInteger.ONE.equals(power))  return base;

由于BigInteger是不可变的并返回新的BigInteger实例,因此您必须累加乘法和加法的结果

and you have to accumulate the result of your multiplication and addition because BigInteger is immutable and returns new BigInteger instance

无限循环是因为您的x永不更改-应该是

x = x.add(BigInteger.ONE);

乘法应更改为

result = result.mulitply(base);

初始结果值应为BigInteger.ONE

where initial result value should be BigInteger.ONE

这篇关于大整数Java幂计算期间的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆