Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find 'n' raise to power 'n' in java

Tags:

java

I am trying to find an efficient way for calculating N^N in java. As the result will be very large for large N, I used BigInteger as my result data type and N is integer. If N becomes large say N=10000000 then it takes more time to calculate the result. Is there any efficient way that will calculate it within a second.

like image 386
Prathamesh Raut Avatar asked Nov 30 '25 00:11

Prathamesh Raut


1 Answers

Handle the log of the number, which is N ln(N), in your program. As N grows, the size of N ln(N) relative to N^N shrinks faster and faster.

The way you would implement this depends on what you need to do. If you don’t need your N^N inside the program, then just forget about it and do it on paper once the program outputs. When you’re handling numbers that big, its log/order of magnitude/the number of digits it has (all of those are synonymous) is most of the essential information. If your program outputs x, you would report that the answer is around e^x, and that would be about all you could say.

If you do need N^N inside your program, then you should still calculate x = ln(N^N) = N ln(N). But then you’re going to have to come up with some creative way of going from x to some value that your program can actually use.

like image 96
Zach Blumenstein Avatar answered Dec 02 '25 14:12

Zach Blumenstein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!