Manipulating BigIntegers in Java Baeldung

I was working on a java program where I need to calculate and store huge values ​​in an array. So far, I am getting the value by inserting the injected variable into an exponential function:

Math.pow(7,x);

      

I decided to store the value in a BigInteger array, but I don't know how to store these regular managed values ​​with the provided BigInteger constructors. For the "x" value, I actually use quite large numbers that trigger the specified value depending on how long it can be stored. I seem to come full circle with every solution I think of ... just do:

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

      

Doesn't work as I am dealing with values ​​greater than 100 as x. What can I do?

+3


source to share


3 answers


Do



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

      

+9


source


Aioobe's answer is already provided suggesting using BigInteger.valueOf correctly, but I want to provide more information.

As he says:

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

      



But let's also take a look at the Java documentation regarding the valueOf () method:

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

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

+3


source


Supply string as parameter to BigInteger constructor, eg.

BigInteger bigInteger = new BigInteger("1000000000000000000000000000000000000000000000000000000000000000000");

      

In your case

 BigInteger bigInteger = new BigInteger("7").pow(x);

      

0


source







All Articles