简体   繁体   中英

Negative exponent at java.base/java.math.BigInteger.pow

How can i fix error Negative exponentat java.base/java.math.BigInteger.pow from my function:

static BigInteger eul(BigInteger n, BigInteger b) {

        BigInteger pattern = (n.add(BigInteger.ONE)).divide(new BigInteger("4"));
        BigInteger result = new BigInteger(String.valueOf(b.pow(pattern.intValue())));

        return result;
    }

error throw at line:

BigInteger result = new BigInteger(String.valueOf(b.pow(pattern.intValue())));

input n=3214315236286878413828554688017932599492010774390476107169160882202257140006023 b=2424542564265464646464646412424987764446756457474245176752585282729789707797971262662662627967

output should be: 2012412197646109946818069059950164564377761312631574365459647649336933671988569

pattern.intValue()

pattern is some enormous number. .intValue() converts that to an int (hence the name), which is why this goes wrong, as this doesn't fit (and happens to turn into a negative number due to how intValue() works when you call that on a bigInteger whose value exceeds what int can represent. The reason only ints go there is because if you put a huge number there, your RAM can't hold it and your CPU would take a few million years to calculate it. There'd be no point.

How do I fix it?

By going back to whomever gave you this assignment. your code has a bug, but reading what it is intending to do, it is ((n+1)/4)^b.

Which is a number that has... a lot a lot of digits. Many, many more than what you expect for output.

Clearly that isn't what you really wanted, or if it is, no computer can calculate this, and the result would be nothing like what you wanted.

Possibly that output really is ((n+1)/4)^b, but mod something. Which the API does support: b.modPow(pattern, FigureOutWhatTheModuloIsAndPutThatHere) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM