3

Possible Duplicate:
The most efficient way to implement an integer based power function pow(int, int)

I know this question is pretty easy but my requirement is that I want to compute x to power x where x is a very large number in the best optimize way possible. I am not a math geek and therefore need some help to figure out the best way possible.

In java, we can use BigInteger but how to optimize the code? Any specific approach for the optimization?

Also using recursion will the large value of x, makes the code slow and prone to stack overflow error?

Eg: 457474575 raise to power 457474575

Community
  • 1
  • 1
learner
  • 1,095
  • 2
  • 18
  • 41

3 Answers3

12

You do realize that the answer to your example is going to be a very very large number, even for a BigInteger? It will have 3961897696 digits!

The best way to work with really large numbers, if you don't need exact precision, is to work with their logarithms instead. To take x to the x power, take the log of x and multiply it by x. If you need to convert it back take e to the x exp(x), except in this case it will almost certainly overflow.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
1

This is one of the simplest optimized approaches:

x^1*x^1=x^2
x^2*x^2=x^4
etc...
x^x = x^(x/2)*x^(x/2)*remainder
Šimon Tóth
  • 35,456
  • 20
  • 106
  • 151
1

((BigInteger) 457474575).pow(457474575);

toto2
  • 5,306
  • 21
  • 24