Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating BigIntegers in Java

I have been working on a java program in which I need to calculate and store immense values into an array. So far, I get the value by plugging in an entered variable into an exponential function:

Math.pow(7,x);

I've decided to store the value into a BigInteger array, but I do not know how to store these regular manipulated values with the provided constructors BigInteger provides. For the 'x' value, I am actually using quite large numbers which launch the specified value over what longs can store. I seem to come full circle with every solution I think of...simply doing:

bigArray[i] = new BigInteger((long)Math.pow(7,x));

Does not work, since I am dealing with values larger than 100 as x. What can I do?

like image 497
Drew Erikson Avatar asked Jun 01 '26 21:06

Drew Erikson


2 Answers

Do

BigInteger bi = BigInteger.valueOf(7).pow(x);
like image 185
aioobe Avatar answered Jun 04 '26 10:06

aioobe


aioobe's answer already provided, suggesting using BigInteger.valueOf is correct, but I want to provide some additional information.

As he says:

BigInteger bi = BigInteger.valueOf(7).pow(x);

But lets also look at the Java documentation with regard to the "valueOf()" method:

"This "static factory method" is provided in preference to a (long) constructor because it allows for reuse of frequently used BigIntegers."

See: http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#valueOf(long)

like image 23
Dexygen Avatar answered Jun 04 '26 10:06

Dexygen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!