First, if you have a specific logarithm operator (many languages provide logarithms only on a base 10or base basis e), you can calculate how (where , obviously, is a base, in your language).logablogxb / logxax
Python is doing better because it can work out a logarithm for an arbitrary base without this complex equality above.
, . , b a ( 1) b a.
, , :
def isPower (num, base):
if base == 1 and num != 1: return False
if base == 1 and num == 1: return True
if base == 0 and num != 1: return False
power = int (math.log (num, base) + 0.5)
return base ** power == num
., , , :
import math
def isPower (num, base):
if base == 1 and num != 1: return False
if base == 1 and num == 1: return True
if base == 0 and num != 1: return False
power = int (math.log (num, base) + 0.5)
return base ** power == num
print isPower (127,2)
print isPower (128,2)
print isPower (129,2)
print
print isPower (26,3)
print isPower (27,3)
print isPower (28,3)
print isPower (3**10,3)
print isPower (3**129,3)
print
print isPower (5,5)
print isPower (1,1)
print isPower (10,1)
, , , , . , isPower(128,2), isPower(verybignum,2).
:
def isPower (num, base):
if base == 1 and num != 1: return False
if base == 1 and num == 1: return True
if base == 0 and num != 1: return False
testnum = base
while testnum < num:
testnum = testnum * base
return testnum == num
, , , .
( 1) , , . , " " .