【问题标题】:Integer expressed in a power form以幂形式表示的整数
【发布时间】:2017-12-31 11:22:46
【问题描述】:

如果对于一些a > 0 和一些x > 1,我们有N = a^x,则据说一个数字N 可以用幂形式表达。

现在要检查这一点,我们可以在两边取日志,等式变为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)

还有其他替代/更好的方法来解决这个问题吗?

【问题讨论】:

  • 这是一道数学题还是编程题?
  • 我打算用来编程但可以当作一道数学题。
  • 时间复杂度不是您的主要问题,浮点精度才是。尝试 n = 76 ** 89 - 1 和 n = 76 ** 89。
  • 即使数字很小log(1<<29) / log(2) != 29,浮点精度也会失败。您可能至少需要x - int(x) < ESP 比较而不是==
  • 好点 @BlownhitherMa 即使 3 ** 5 失败。

标签: python python-3.x math


【解决方案1】:

更好的方法是以下算法:

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)

此算法将比线性算法快得多。我认为它是对数的,但没有时间检查它。

【讨论】:

  • root(N, i) 在 i 为 2 时为平方根,在 i 为 3 时为立方根,依此类推。
  • 它是对数的,因为它在 i 达到 N 的以二为底的对数处或之前停止。 (如果 iN 的以二为底的对数,则 root(N, i) 为 2。 )
  • @LajosArpad 谢谢,这就是我要找的:)
  • @Demonking28 欢迎您。如果我的回答解决了您的问题,那么您可以考虑接受它作为正确的解决方案。
猜你喜欢
  • 2016-12-20
  • 2019-05-03
  • 1970-01-01
  • 2018-01-17
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多