wasp256
wasp256

Reputation: 6242

Figure out if exponent is above long threshold before calculation

I'm using the math library in combination with the JexlEngine to calculate different equations. In this equations I also have the pow function. The problem is that when I have huge numbers like math.pow(99999, 10000), jexl tries to evaluate it and that takes a lot of time and CPU usage. The evaluation should not be done if the solution exceeds the max Long value. Is there a way to find out before evaluating the power if it is bigger then a max Long?

Upvotes: 0

Views: 125

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533510

You can compare the exponent to

double base = 99999;
double maxExp = Math.log(Long.MAX_VALUE)/Math.log(base);

if the power is above maxExp, you will get an overflow.

Upvotes: 3

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

You could try

static final BigInteger BigLongMax = BigInteger.valueOf(Long.MAX_VALUE);
...
BigInteger.valueOf(99999).pow(10000).compareTo(BigLongMax);

Upvotes: 0

Related Questions