3

I was looking at the wikipedia page on primes and of course, I came across the largest known prime which is 2^43,112,609 − 1. This number is exceptionally large. So for fun, I decided to put this into BigInteger. To calculate this, it would take a very long time (I gave up after a while).

Is there any faster of computing a very large number like this? Or is BigInteger and a better computer the only way? Any reduction of time would be great.

*Note that my question has nothing to do with finding prime numbers. I'm asking if there is a better way to compute the number 2^43,112,609 − 1.

Mysticial
  • 464,885
  • 45
  • 335
  • 332
Jeel Shah
  • 3,274
  • 17
  • 47
  • 68

3 Answers3

2

The problem with BigInteger is that it isn't meant for such large numbers. Last time I checked, it was still using quadratic run-time algorithms for both its multiplication and it's base conversion.

So the reason why computing 2^43,112,609 − 1 takes so long is that it's just huge - and you're trying to put that through a quadratic run-time algorithm.

Unfortunately, if you want something faster you will need to use a better bignum library. In C/C++ you have GMP. There are Java wrappers for it if you google around.


*Note that computing 2^43,112,609 − 1 itself is fast since you can do it with just a shift. The slow part is printing out as a string in base 10. Java still uses an O(n^2) algorithm for this conversion.

Efficient programs will be able do this conversion in roughly O(n * log(n)^2) time - which will be under a minute using the latest version of GMP on most up-to-date machines today.

Mysticial
  • 464,885
  • 45
  • 335
  • 332
1

As noted above by Mysticial, BigInteger isn't really meant to handle such large numbers. Here's a link to a Java wrapper of GMP. I haven't used it, but I've heard a few positive things, so it may be worth giving it a try:

Java wrapper for GMP

Shaun
  • 2,446
  • 19
  • 33
0

BigInteger has a pow method, which is likely the best for handling large numbers. Check the Javadoc for more.

Also, as explained in the linked question @prusswan brought up, many of those answers also show primegen algorithms which would help.

Jon Egeland
  • 12,470
  • 8
  • 47
  • 62
  • Actually, In case of OP's case, using a `shiftLeft` will be more efficient than `pow`, since it's `2` – st0le Dec 08 '11 at 06:01