As homework, I should implement a divide and conquer approach for exponentiation of big integers. I know Karatsuba's algorithm for multiplication, what divide and conquer algorithm could I apply to get the result of x^y, both being large integers?.
3 Answers
There are a couple of algorithms grouped together under the name square and multiply. You could get some inspiration from them.

- 60,705
- 7
- 138
- 176
Consider x^256. Rather than doing x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x*x
, one could do (...(((x^2)^2)^2...)^2 a mere 8 times (log2 of 256).
In general, write out your exponent as binary and apply the exponent-of-sum rule. Then as you calculate successive powers of x, multiply them in to an accumulator if they appear in the exponent (they will appear if there is a "1" in that digit in the exponent).

- 88,546
- 24
- 137
- 145
-
what's the exponent-of-sum rule? – andandandand May 14 '11 at 21:07
-
you are referring to the 2^k-ary method in the wikipedia link, righ? – andandandand May 14 '11 at 21:08
-
The expression (((x^2)^2)^2) is equal to x^8 not to x^256. – Javier Ruiz Sep 30 '20 at 22:44
Here's a nice recursive algorithm.
int pow(int a,int b)
{
if(b == 0) return 1;
else if(b % 2 == 0) return pow(a,b/2) * pow(a,b/2);
else return a * pow(a,b-1);
}

- 2,877
- 1
- 26
- 29