How to make perfect power algorithm more efficient?

后端 未结 4 631
长发绾君心
长发绾君心 2021-01-26 02:31

I have the following code:

def isPP(n):
  pos = [int(i) for i in range(n+1)]
  pos = pos[2:] ##to ignore the trivial n** 1 == n case
  y = []
  for i in pos:
            


        
4条回答
  •  别那么骄傲
    2021-01-26 02:57

    I think a better way would be implementing this "hack":

    import math
    
    def isPP(n):
        range = math.log(n)/math.log(2)
        range = (int)(range)
        result = []
        for i in xrange(n):
            if(i<=1):
                continue
            exponent = (int)(math.log(n)/math.log(i))
            for j in [exponent-1, exponent, exponent+1]:
                if i ** j == n:
                    result.append([i,j])
        return result
    
    print isPP(10000)
    

    Result:

    [[10,4],[100,2]]
    

    The hack uses the fact that:

    if log(a)/log(b) = c,
        then power(b,c) = a
    

    Since this calculation can be a bit off in floating points giving really approximate results, exponent is checked to the accuracy of +/- 1.

    You can make necessary adjustments for handling corner cases like n=1, etc.

提交回复
热议问题