Search code examples
javaalgorithm

How to write a power function for big numbers in Java


Suppose I want to calculate 2^10000 using Math.pow(). For which my code is-

long num = (long)Math.pow(2, 10000);
System.out.println(num);

Here I'm getting output as 9223372036854775807 which I guess is the limit of long. But if I write like this-

double n = Math.pow(2, 10000);
System.out.println(n); 

the o/p is Infinity which is a bit weird. Anyone please help me with this.


Solution

  • This will work, but be aware that BigInteger is not very efficient and I don't consider it suitable for production work for math problems.

    public static void main( String[] args ) {
      BigInteger two = new BigInteger( "2" );
      BigInteger twoToTenThousand = two.pow( 10000 );
      System.out.println( twoToTenThousand );
    }