0

I have code that will get the exponent value from given input:

BigInteger a= new BigInteger(2,10);       
BigInteger b; 
b=a.pow(9999999999);

It is working when value is lower than 7 digits. For example:

BigInteger a= new BigInteger(2,10);       
BigInteger b; 
b=a.pow(1234567);

Does my code make it possible or is it not possible to have 10 digit in the exponent?

I'm using JDK 1.8.

khelwood
  • 55,782
  • 14
  • 81
  • 108

2 Answers2

1

pow's parameter is an int. The range of int is -2147483648 to 2147483647, so the answer is it depends on which 10 digits you use. If those 10 digits are 1234567890, that's fine, it's in range (though potentially you'll get a really, really big BigInteger which may push your memory limits); if they're 9999999999 as in your question, that's not fine, it's out of range.

E.g., this compiles:

int a = 1234567890;

This does not:

int b = 9999999999;
        ^--------------- error: integer number too large: 9999999999
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • so if do i need to change my code or find another way to do the task ? – Drian Drian Oct 01 '19 at 08:39
  • @DrianDrian - Yes, . But two things: 1. `BigInteger` isn't required to support a number in the range you want. It's only required to support numbers up to 2 to the power of `Integer.MAX_VALUE`. 2. Even if it did, it would take a **long** time to compute, and the result would be a ***truly massive*** number. I suspect you'd run out of memory. Consider that 2 to the power of just 999 is roughly 536xxx where xxx is **297** zeros. – T.J. Crowder Oct 01 '19 at 08:53
1

BigInteger.pow() only exists for int parameters, so you can't take the power bigger than Integer.MAX_VALUE at once.

Those numbers would also be incredibly big (as in "rapidly approaching and passing the number of particles in the observable universe), if you could do it, and there are very few uses for this.

Note that the "power with modulus" operation which is often used in cryptography is implemented using BigInteger.modPow() which does take BigInteger arguments and can therefore handle effectively arbitrarily large values.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • So i should be using modPow for this to work @joachim – Drian Drian Oct 01 '19 at 08:39
  • @DrianDrian: it really depends on what you need it for, so I don't know. If you were planning to call `pow` and then call `mod` on the number, then yes `modPow` will produce the same result, be *much, much faster* and also work with significantly bigger numbers. If you actually wanted to continue handling the immensely big number that `pow` produces in some other way, then `modPow` is *not* a replacement that helps you. – Joachim Sauer Oct 01 '19 at 08:41