将一个数字拆分为两个幂的总和

时间:2018-02-11 10:15:23

标签: python algorithm math optimization

x是我的输入。 我需要找到i,j> = 0和n,m> 1,例如x = i**m+j**n

现在我一直在这样做,但这是减缓的方法!我怎样才能改进它?

from math import sqrt
import numpy as np

def check(x):
    for i in range(1,int(np.ceil(sqrt(x)))):
        for j in range(1,int(np.ceil(sqrt(x)))):
            for m in range(2,x/2+1):
                for n in range(2,x/2+1):
                    if((pow(i,m) +pow(j,n))==x):
                        print 'Yes';
                        return ;
    print 'No';
谢谢你!

3 个答案:

答案 0 :(得分:2)

您可以通过查找小于x的所有幂(i ** m)来反转该过程。然后你只需检查这些功能中是否有任何一对加起来。

def check(x):
    all_powers = set([1]) #add 1 as a special case

    #find all powers smaller than x 
    for base in range(2,int(math.ceil(sqrt(x)))):
        exponent = 2;
        while pow(base, exponent) < x:
            all_powers.add(pow(base, exponent))
            exponent+=1

    #check if a pair of elements in all_powers adds up to x
    for power in all_powers:
        if (x - power) in all_powers:
            print 'Yes'
            return
    print 'No'

上面的代码很简单,但可以进行优化,例如,通过集成检查,如果一对在while循环中加起来就可以在大多数情况下提前停止。

答案 1 :(得分:1)

这里会不时出现一个问题,即确定正整数是否是另一个正整数的整数幂。即给定正整数z找到正整数jn,使得z == j**n。这可以在时间复杂度O(log(z))中完成,因此速度非常快。

所以找到或开发这样一个例程:如果is_a_power(z)具有(j, n)的强大功能,如果不是z,则将其称为(0, 0),返回元组i。然后循环mx - i**m,然后检查x是否为幂。当它成为一体时,你就完成了。

我会让你从这里完成代码,除了一个指针。鉴于ii > 1 m,您可以找到i**m <= x的上限,m <= log(x) / log(i)

i == 1

请注意,i**m是一种特殊情况,因为m在这种情况下实际上并不依赖于{{1}}。

答案 2 :(得分:0)

from math import sqrt
import numpy as np
def build(x):
# this function creates number that are in form of
# a^b such that a^b <= x and b>1
  sq=sqrt(x);
  dict[1]:1; # 1 is always obtainable
  dict[0]:1; # also 0 is always obtainable
  for i in range(1,sq): # try the base
    number=i*i; # firstly our number is i^2
    while number<=x: 
      dict[number]:1; # this number is in form of a^b
      number*=i; # increase power of the number
def check(x):
  sq=sqrt(x);
  for i in range(1,sq): # we will try base of the first number
    firstnumber=1;
    while firstnumber<=x: # we are trying powers of i
      remaining=x-firstnumber; # this number is remaining number when we substract firstnumber from x
      if dict[remaining]==1: # if remaining number is in dictionary which means it is representable as a^b
        print("YES");  # then print YES
        return ;
      firstnumber*=i; # increase the power of the base
  print("NO");
  return ;

以上代码适用于O(sqrt(x)* log(x)* log(x)),速度更快。

您可以阅读代码中的注释来理解它。