O(lg n⋅(lg lg n)2)
ab=nb<lg n
ba
ablg b=lg lg na
Aalg A
b lg a=lg n
lg A=lg nb
∑lg A=lg n⋅(11+12+...+1B)=lg n⋅lg B=lg n⋅lg lg n
O(lg n⋅lg lg n)
abO(lg n⋅(lg lg n)2)
ps: Semua lg adalah basis 2.
Kode python:
#--- a^n ---------------------------------------
def fast_exponentation(a, n):
ans = 1
while n:
if n & 1 : ans = ans * a
a = a * a
n >>= 1
return ans
#------------------------------------------
# Determines whether n is a power a ^ b, O(lg n (lg lg n) ^ 2)
def is_power(n):
if (- n & n) == n: return True # 2 ^ k
lgn = 1 + ( len( bin ( abs ( n ) ) ) - 2)
for b in range(2,lgn):
# b lg a = lg n
lowa = 1L
higha = 1L << (lgn / b + 1)
while lowa < higha - 1:
mida = (lowa + higha) >> 1
ab = fast_exponentation(mida,b)
if ab > n: higha = mida
elif ab < n: lowa = mida
else: return True # mida ^ b
return False