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;
I run this and apparently x never equals power. Any help is appreciated.
You should do
and you have to accumulate the result of your multiplication and addition because BigInteger is immutable and returns new BigInteger instance
The infinite loop is because your x NEVER changes – should be
multiplication should change to
where initial result value should be BigInteger.ONE