1

Possible Duplicate:
Efficient Exponentiation For HUGE Numbers (I’m Talking Googols)

I'm trying to create some code to find the value of x^y (non-negative x's and y's). The catch is that I'm extending an ISA, and there is no multiplication built it. I think I've got a solution using a nested loop and addition, but that could be pretty inefficient, especially for higher powers and bases.

I was wondering if there is an efficient way to calculate this using bitwise shifts or some other clever method? I've worked out something of an algorithm for even bases that I think works, but I can't get anything for odd bases figured out. Of course, it would be better if there was a solution that worked for both odds and evens to save processing time figuring out whether the number is odd or even.

For evens my solution was right shifting the base to divide it by 2 and performing that many left shifts (times 2 for each shift) times the exponent-1.

Example: 4^3

4 RS = 2 So 2 left shifts is like multiplying by 4, do that 2 times (exponent-1) to get 4*4*4 = 4^3

So, keeping in mind that this only needs to work for positive x's and y's, does anybody have a good solution? Thanks in advance.

Community
  • 1
  • 1
user1877760
  • 263
  • 2
  • 9
  • 2
    http://en.wikipedia.org/wiki/Exponentiation#Efficient_computation_of_integer_powers http://en.wikipedia.org/wiki/Exponentiation_by_squaring – nhahtdh Dec 05 '12 at 05:36
  • 1
    http://stackoverflow.com/questions/8771713/efficient-exponentiation-for-huge-numbers-im-talking-googols – nhahtdh Dec 05 '12 at 05:42
  • Thank you for the links, it looks like these will be very helpful. Sorry I didn't mention, x and y are both integers. – user1877760 Dec 05 '12 at 05:49
  • Then it's fine. It will be even crazier when y is in real. – nhahtdh Dec 05 '12 at 05:54

0 Answers0