The following function calculates a^b. assume that we already have a prime_list which contain all needed primes and is sorted from small to large. The code is written in python.
def power(a,b):
if b == 0:
return 1
prime_range = int(sqrt(b)) + 1
for prime in prime_list:
if prime > prime_range:
break
if b % prime == 0:
return power(power(a, prime), b/prime)
return a * power(a, b-1)
How to determine its time complexity? p.s. The code isn't perfect but as you can see the idea is using primes to reduce the number of times of arithmetic operations. I am still looking for an ideal implementation so please help if you come up with something. Thx!