2

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

The only two methods that I know is,

  1. A single for loop: extremely slow

  2. Rewrite enter image description here recursively calculate.

I wonder is there a faster algorithm than these two? Any bitwise technique are welcome. Thank you.

C# demos for the two algorithms:

     class Math {
        static public Int64 recurPow( Int64 a, Int64 e ) {
            if ( e == 0 )
                return 1;
            if ( e == 1 )
                return a;
            if ( ( e % 2 ) == 0 )
                return recurPow( a * a, e / 2 );
            else
                return recurPow( a * a, ( e - 1 ) / 2 );
        }

        static public Int64 iterPow( Int64 a, Int64 e ) {
            Int64 result = a;
            for ( Int64 i = 1; i < e; ++i )
                result *= a;
            return result;
        }
    }
Community
  • 1
  • 1
roxrook
  • 13,511
  • 40
  • 107
  • 156

1 Answers1

3

The optimal algorithm is NP-complete, see http://en.wikipedia.org/wiki/Addition-chain_exponentiation

That page also links to a number of heuristic algorithms that give pretty good answers, you probably want one of them.

Are you doing comp3212 as well?

riri
  • 519
  • 4
  • 15
  • Thanks. I'm not in that class, just get to know it when reading a math book. – roxrook Apr 24 '11 at 23:48
  • Well we had that problem assigned to us. The lecturer has a habit of "accidentally" assigning unsolvable problems. – riri Apr 24 '11 at 23:57