如果对于某些N
和某些a > 0
,我们有x > 1
,则表示数字N = a^x
可以表格形式表达。
现在要检查一下,我们可以记录双方,方程变为log(n)/log(a)=x
所以通过从(2,sqrt(n))
迭代,如果有任何数字给出x
作为整数而不是该数字权力x
可以表示为N
。
以下是检查相同
的代码from math import log,sqrt,floor
n=int(input())
t=floor(sqrt(n))+1
flag=False
for i in range(2,t):
x=log(n)/log(i)
if x==int(x):
print("YESSSSSSSSSSSSS!")
flag=True
break
if not flag:
print("Nooooooooooooooooooo!")
时间复杂度: O ( n )
还有其他替代/更好的解决方法吗?
答案 0 :(得分:5)
更好的方法是以下算法:
x <- 0
i <- 2
found <- false
do
x <- root(N, i)
if (x is integer) then
found <- true
end if
i <- i + 1
while (x >= 2) and (not found)
此算法将比线性快得多。我认为它是对数的,但没有时间检查它。