Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

divide and conquer approach for exponentiation?

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?.

like image 518
andandandand Avatar asked May 13 '11 23:05

andandandand


2 Answers

There are a couple of algorithms grouped together under the name square and multiply. You could get some inspiration from them.

like image 198
Femaref Avatar answered Sep 20 '22 20:09

Femaref


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).

See http://en.wikipedia.org/wiki/Exponentiation_by_squaring

like image 37
ninjagecko Avatar answered Sep 21 '22 20:09

ninjagecko