You need to calculate much less when you reuse results.
For Example:
5^8 = 5^4*5^4 = 5^2*5^2*5^2*5^2 = 5*5*5*5*5*5*5*5
You don't need to do all 7 multiplications, only 5*5, 5^2*5^2, 5^4*5^4 (3 multiplications)
The following code is Python code (because i wanted to easily test it), but I hope you see the point.
def powBase10(a,n):
if(n==0):
return 1
x=powBase10(a, int(n/10))
if(n%10==0):
return (x*x*x*x*x*x*x*x*x*x)
if(n%10==1):
return (a*x*x*x*x*x*x*x*x*x*x)
if(n%10==2):
return (a*a*x*x*x*x*x*x*x*x*x*x)
if(n%10==3):
return (a*a*a*x*x*x*x*x*x*x*x*x*x)
if(n%10==4):
return (a*a*a*a*x*x*x*x*x*x*x*x*x*x)
if(n%10==5):
return (a*a*a*a*a*x*x*x*x*x*x*x*x*x*x)
if(n%10==6):
return (a*a*a*a*a*a*x*x*x*x*x*x*x*x*x*x)
if(n%10==7):
return (a*a*a*a*a*a*a*x*x*x*x*x*x*x*x*x*x)
if(n%10==8):
return (a*a*a*a*a*a*a*a*x*x*x*x*x*x*x*x*x*x)
if(n%10==9):
return (a*a*a*a*a*a*a*a*a*x*x*x*x*x*x*x*x*x*x)
def powBase2(a,n):
if(n==0):
return 1
x=powBase2(a, int(n/2))
if(n%2==0):
return (x*x)
if(n%2==1):
return (a*x*x)
The code should be faster when you use base 2 instead of base 10.
The reason why should adjust the algorithm to your base is, that the division by the base can be done by deleting the last digit, so there is no real calculation needed for division.
The number of multiplications you need should be logarithmic with this approach instead of linear so it should be no problem with a few hundred digits.
You could optimize the base-10 code again with the same approach
for example instead of:
x*x*x*x*x*x
use:
y=x*x
y=y*y*y
But this will only result in a constant speedup.